Skip to content

Commit 47cc584

Browse files
committed
Break down MCP route registrations
1 parent 078dc8f commit 47cc584

14 files changed

Lines changed: 2217 additions & 2095 deletions

File tree

src/app/[transport]/route.ts

Lines changed: 2 additions & 2095 deletions
Large diffs are not rendered by default.

src/lib/mcp/kernel-client.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Kernel } from "@onkernel/sdk";
2+
3+
export function createKernelClient(apiKey: string) {
4+
const headers: Record<string, string> = {
5+
"X-Source": "mcp-server",
6+
"X-Referral-Source": "mcp.onkernel.com",
7+
};
8+
9+
const projectId = process.env.KERNEL_PROJECT;
10+
if (projectId) {
11+
headers["X-Kernel-Project-Id"] = projectId;
12+
}
13+
14+
return new Kernel({
15+
apiKey,
16+
baseURL: process.env.API_BASE_URL,
17+
defaultHeaders: headers,
18+
});
19+
}
20+
21+
export type KernelClient = ReturnType<typeof createKernelClient>;

src/lib/mcp/prompts.ts

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2+
import { z } from "zod";
3+
4+
export function registerKernelPrompts(server: McpServer) {
5+
// MCP Prompt explaining Kernel concepts
6+
server.prompt(
7+
"kernel-concepts",
8+
"Explain Kernel's core concepts and capabilities for AI agents working with web automation",
9+
{
10+
concept: z
11+
.enum(["browsers", "apps", "overview"])
12+
.describe(
13+
"The specific concept to explain: browsers (sessions), apps (code execution), profiles (browser auth), or overview (all concepts)",
14+
),
15+
},
16+
async ({ concept }) => {
17+
const explanations = {
18+
browsers: `## 🌐 Browsers (Sessions)
19+
20+
**What they are:** Kernel provides serverless browsers-as-a-service that run in isolated cloud environments. Each browser is a complete, sandboxed instance that can automate any website.
21+
22+
**Key capabilities:**
23+
- **Instant launch** - Browsers start in seconds, not minutes
24+
- **Full isolation** - Each browser runs in its own virtual machine
25+
- **Parallel scaling** - Run hundreds or thousands of concurrent browsers
26+
- **Live view** - Human-in-the-loop workflows with real-time browser viewing
27+
- **Replays** - Record and review past browser sessions as videos
28+
- **CDP integration** - Connect with Playwright, Puppeteer, or any CDP-compatible tool
29+
- **Profiles** - Save and reuse authentication cookies and login data across sessions
30+
31+
**Use cases:** Web scraping, form automation, testing, data extraction, user journey simulation, and any task requiring browser interaction.
32+
33+
**Session options:**
34+
- **Timeout** - Configure browser timeout up to 72 hours for long-running sessions
35+
- **Profiles** - Save and reuse authentication cookies and login data`,
36+
37+
apps: `## 🚀 Apps (Code Execution Platform)
38+
39+
**What they are:** Kernel's app platform lets you deploy, host, and invoke browser automation code in production without managing infrastructure.
40+
41+
**Key capabilities:**
42+
- **Serverless execution** - Deploy automation code that runs on-demand
43+
- **Auto-scaling** - Automatically handles traffic spikes and resource allocation
44+
- **Seamless integration** - Apps can create and manage browsers programmatically
45+
- **Production ready** - Built-in monitoring, logging, and error handling
46+
- **Multiple languages** - Support for Python, TypeScript, and more
47+
48+
**Development workflow:**
49+
1. Write your automation code
50+
2. Deploy to Kernel's platform
51+
3. Invoke via API or MCP tools
52+
4. Monitor execution and results
53+
54+
**Use cases:** Scheduled web scraping, API endpoints for browser automation, complex multi-step workflows, and production automation services.`,
55+
56+
overview: `## 🎯 Kernel Platform Overview
57+
58+
**What Kernel is:** A developer platform that provides browsers-as-a-service for AI agents to access websites. Our API and MCP server allows web agents to instantly launch browsers in the cloud and automate anything on the internet.
59+
60+
**Core Concepts:**
61+
62+
### 🌐 Browsers (Sessions)
63+
Serverless browsers that run in isolated cloud environments. Each browser can automate any website with full CDP compatibility, live viewing, replay capabilities, and profiles for authentication.
64+
65+
### 🚀 Apps (Code Execution)
66+
Production-ready platform for deploying and hosting browser automation code. Handles auto-scaling, monitoring, and execution without infrastructure management.
67+
68+
**Why developers choose Kernel:**
69+
- **Performance** - Crazy fast browser launch times
70+
- **Developer experience** - Simple APIs and comprehensive tooling
71+
- **Production ready** - Handles bot detection, authentication, scaling, and observability
72+
- **Cost effective** - Only pay for active browser time
73+
- **Reliable** - Built for enterprise-scale automation
74+
75+
**Perfect for:** AI agents, web automation, testing, scraping, form filling, and any task requiring browser interaction.`,
76+
};
77+
78+
return {
79+
messages: [
80+
{
81+
role: "assistant",
82+
content: {
83+
type: "text",
84+
text: explanations[concept],
85+
},
86+
},
87+
],
88+
};
89+
},
90+
);
91+
92+
// Debug Browser Session Prompt
93+
server.prompt(
94+
"debug-browser-session",
95+
"Comprehensive debugging guide for troubleshooting Kernel browser sessions. Provides a systematic approach to diagnose VM issues, network problems, Chrome errors, and more.",
96+
{
97+
session_id: z
98+
.string()
99+
.describe(
100+
"The browser session ID to debug (e.g., 'abc123example456xyz')",
101+
),
102+
issue_description: z
103+
.string()
104+
.describe(
105+
"Description of the issue you're experiencing (e.g., 'ERR_HTTP2_PROTOCOL_ERROR when navigating to a specific site', 'browser not responding', 'page not loading')",
106+
),
107+
},
108+
async ({ session_id, issue_description }) => {
109+
const debugGuide = `# 🔍 Browser Session Debugging Guide
110+
111+
**Session ID:** \`${session_id}\`
112+
**Reported Issue:** ${issue_description}
113+
114+
---
115+
116+
## Tools
117+
118+
**Use the Kernel CLI for debugging.** It provides full access to browser sessions, VM logs, and process execution.
119+
120+
Install: \`brew install onkernel/tap/kernel\` or \`npm install -g @onkernel/cli\`
121+
122+
**Explore available commands recursively:**
123+
\`\`\`bash
124+
kernel --help
125+
kernel browsers --help
126+
kernel browsers fs --help
127+
kernel browsers process --help
128+
kernel browsers playwright --help
129+
\`\`\`
130+
131+
**MCP Exception:** The \`computer_action\` MCP tool with action "screenshot" is useful since it returns images directly to the agent.
132+
133+
---
134+
135+
## Key CLI Commands for Debugging
136+
137+
### Check session status
138+
\`\`\`bash
139+
kernel browsers get ${session_id}
140+
\`\`\`
141+
142+
### Take a screenshot (or use MCP computer_action with action "screenshot")
143+
\`\`\`bash
144+
kernel browsers screenshot ${session_id}
145+
\`\`\`
146+
147+
### Execute Playwright code
148+
\`\`\`bash
149+
kernel browsers playwright execute ${session_id} "return { url: page.url(), title: await page.title() }"
150+
\`\`\`
151+
152+
### Read VM log files
153+
\`\`\`bash
154+
kernel browsers fs read-file ${session_id} --path /var/log/supervisord.log
155+
kernel browsers fs read-file ${session_id} --path /var/log/supervisord/chromium
156+
kernel browsers fs read-file ${session_id} --path /var/log/supervisord/neko
157+
\`\`\`
158+
159+
### List files in the VM
160+
\`\`\`bash
161+
kernel browsers fs ls ${session_id} --path /var/log
162+
\`\`\`
163+
164+
### Execute commands inside the VM
165+
\`\`\`bash
166+
kernel browsers process exec ${session_id} -- curl -I https://example.com
167+
kernel browsers process exec ${session_id} -- cat /etc/resolv.conf
168+
\`\`\`
169+
170+
### Check cookies via Playwright
171+
\`\`\`bash
172+
kernel browsers playwright execute ${session_id} "const cookies = await page.context().cookies(); return { count: cookies.length, domains: [...new Set(cookies.map(c => c.domain))] }"
173+
\`\`\`
174+
175+
---
176+
177+
## Common Issues & Solutions
178+
179+
### Network Errors (ERR_HTTP2_PROTOCOL_ERROR, ERR_CONNECTION_RESET, etc.)
180+
181+
**Bot detection is a common cause of network errors.** Many sites use CDNs like Cloudflare, Imperva, or Akamai that fingerprint browsers and block automation.
182+
183+
**Signs of bot detection:**
184+
- curl works from the VM but Chrome shows an error
185+
- "Access Denied", CAPTCHA pages, or "Checking your browser..." messages
186+
- \`stealth: false\` in browser config (check with manage_browsers action "get")
187+
188+
**Solutions:** Use \`stealth: true\`, use profiles with real auth, or try shorter session lifetimes.
189+
190+
### Browser Not Responding
191+
**Cause:** Chrome process crashed or hung
192+
**Check:** Supervisor logs for chromium restart events
193+
**Solutions:**
194+
1. Check if timeout was reached
195+
2. Look for memory issues in logs
196+
3. Create a new browser session
197+
198+
### Page Not Loading
199+
**Cause:** Network, DNS, or proxy issues
200+
**Check:**
201+
1. Test curl from inside VM
202+
2. Check /etc/resolv.conf for DNS config
203+
3. Verify proxy settings if using one
204+
205+
### Live View Not Working
206+
**Cause:** Neko/WebRTC issues
207+
**Check:** Neko logs for connection errors
208+
**Solutions:**
209+
1. Check for firewall blocking WebRTC
210+
2. Verify browser is not in headless mode
211+
212+
---
213+
214+
## Expected Log Entries (Normal Operation)
215+
216+
These are **normal** and don't indicate problems:
217+
- \`Failed to call method: org.freedesktop.DBus.Properties.GetAll\` - DBus permission (expected in container)
218+
- \`vkCreateInstance: Found no drivers\` - No GPU in VM (expected)
219+
- \`DEPRECATED_ENDPOINT\` for GCM - Google deprecation (harmless)
220+
- \`SharedImageManager::ProduceMemory\` errors - GPU-related (not critical)
221+
222+
---
223+
224+
## Debugging Checklist
225+
226+
- [ ] Session exists and is active
227+
- [ ] Screenshot shows expected content (or reveals error)
228+
- [ ] Current URL is as expected
229+
- [ ] Supervisor logs show all services running
230+
- [ ] Network connectivity works (curl test)
231+
- [ ] No critical errors in chromium logs
232+
- [ ] Cookies/session state is correct
233+
234+
---
235+
236+
## Next Steps
237+
238+
Based on your issue "${issue_description}", start with:
239+
240+
1. **Get browser info** to confirm session is active
241+
2. **Take screenshot** to see current state
242+
3. **Check page URL** to see if on error page
243+
4. **Test network** if seeing connection errors
244+
5. **Review logs** for specific error patterns`;
245+
246+
return {
247+
messages: [
248+
{
249+
role: "assistant",
250+
content: {
251+
type: "text",
252+
text: debugGuide,
253+
},
254+
},
255+
],
256+
};
257+
},
258+
);
259+
}

src/lib/mcp/register.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2+
import { registerKernelPrompts } from "@/lib/mcp/prompts";
3+
import { registerAppCapabilities } from "@/lib/mcp/tools/apps";
4+
import { registerBrowserPoolCapabilities } from "@/lib/mcp/tools/browser-pools";
5+
import { registerBrowserCapabilities } from "@/lib/mcp/tools/browsers";
6+
import { registerComputerActionTool } from "@/lib/mcp/tools/computer-action";
7+
import { registerDocsTools } from "@/lib/mcp/tools/docs";
8+
import { registerExtensionTools } from "@/lib/mcp/tools/extensions";
9+
import { registerPlaywrightTool } from "@/lib/mcp/tools/playwright";
10+
import { registerProfileCapabilities } from "@/lib/mcp/tools/profiles";
11+
import { registerProxyTools } from "@/lib/mcp/tools/proxies";
12+
import { registerShellTool } from "@/lib/mcp/tools/shell";
13+
14+
export function registerMcpCapabilities(server: McpServer) {
15+
registerProfileCapabilities(server);
16+
registerKernelPrompts(server);
17+
registerDocsTools(server);
18+
registerBrowserCapabilities(server);
19+
registerBrowserPoolCapabilities(server);
20+
registerProxyTools(server);
21+
registerExtensionTools(server);
22+
registerAppCapabilities(server);
23+
registerComputerActionTool(server);
24+
registerShellTool(server);
25+
registerPlaywrightTool(server);
26+
}

0 commit comments

Comments
 (0)