Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
6d1ab5d
feat: add managed auth MCP app
rgarcia Jul 27, 2026
d9f78be
feat: automatically resume agent after managed auth
rgarcia Jul 28, 2026
8602a92
feat: add managed auth panel close control
rgarcia Jul 28, 2026
116200a
feat: await managed auth without prompt injection
rgarcia Jul 28, 2026
47e0830
fix: fail closed on non-Apps hosts, Bun-pinned CI, reauth wait guards
rgarcia Jul 30, 2026
55b2569
fix: close Bugbot round-2 findings on managed-auth MCP app
rgarcia Jul 30, 2026
7f5c6d2
fix: close Bugbot round-3 findings on managed-auth MCP app
rgarcia Jul 30, 2026
0df1c59
fix: close Bugbot round-4 findings on managed-auth waits
rgarcia Jul 30, 2026
2a40830
fix: close Bugbot round-5 findings on marker identity and relay JWTs
rgarcia Jul 30, 2026
b67c105
chore: scope PR to managed auth MCP app
rgarcia Jul 30, 2026
1dec6d2
fix: close scoped managed-auth Bugbot findings
rgarcia Jul 30, 2026
855a54e
fix: align managed auth app with guarded wait state
rgarcia Jul 30, 2026
f2a173b
fix: preserve non-app managed auth workflows
rgarcia Jul 31, 2026
67d1758
fix: make managed auth app strictly additive
rgarcia Jul 31, 2026
e7753cd
Merge remote-tracking branch 'origin/main' into rgarcia/managed-auth-…
rgarcia Jul 31, 2026
eef1837
refactor: strictly additive manage_auth_connections and faithful App …
rgarcia Jul 31, 2026
cc5e74b
fix: harden managed auth capability and relay boundaries
rgarcia Jul 31, 2026
eb84e39
refactor: remove managed auth text-only launcher
rgarcia Jul 31, 2026
53c01fa
fix: remove managed auth loading flash
rgarcia Jul 31, 2026
9f8e329
fix: focus managed auth form fields
rgarcia Jul 31, 2026
970d142
chore: version managed auth app resource
rgarcia Jul 31, 2026
f113e5a
feat: configure managed auth observability
rgarcia Jul 31, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ NEXT_PUBLIC_CLERK_DOMAIN=<x>.clerk.accounts.dev
# API Configuration - Only needed to set the Kernel SDK base url
API_BASE_URL=<x>

# Public origin of this MCP server. The Managed Auth MCP App connects only to
# the narrowly scoped same-origin relay. Local development: http://localhost:3002
MANAGED_AUTH_APP_ORIGIN=https://mcp.onkernel.com

# Mintlify API Configuration - Only needed for the search_docs tool call
MINTLIFY_ASSISTANT_API_TOKEN=mint_dsc_<x>
MINTLIFY_DOMAIN=<x>

# Optional MCP toolset gating. Comma-separated values.
# Example: api_keys hides manage_api_keys so deployments can opt out of key management.
# Supported: apps, api_keys, browser_pools, browsers, computer, docs, extensions, playwright, profiles, projects, proxies, replays, shell
# Supported: apps, api_keys, auth_connections, browser_pools, browsers, computer, docs, extensions, playwright, profiles, projects, proxies, replays, shell
# KERNEL_MCP_DISABLED_TOOLSETS=api_keys

# Redis Configuration
Expand Down
13 changes: 12 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,20 @@ jobs:
steps:
- uses: actions/checkout@v4

# Pin Bun: the managed-auth App bundle check is byte-exact and Bun's
# minifier output can change between releases. Regenerate the bundle
# with this exact version when bumping it.
- uses: oven-sh/setup-bun@v2
with:
bun-version: "1.3.3"

- run: bun install --frozen-lockfile

- name: Check managed-auth App bundle
run: bun run check:managed-auth-app

- name: Type check
run: bunx tsc --noEmit
run: bunx tsc --noEmit --incremental false

- name: Test
run: bun test
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
src/lib/mcp/apps/generated/managed-auth-app.ts
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,11 @@ Many other MCP-capable tools accept:

Configure these values wherever the tool expects MCP server settings.

## Tools (16 total)
## Tools (17 model-facing, plus 1 app-only helper)

Each Kernel feature has a single `manage_*` tool with an `action` parameter, keeping the tool set small and consistent. Five standalone tools handle high-frequency workflows.
Each Kernel feature has a single `manage_*` tool with an `action` parameter, keeping the tool set small and consistent. Standalone tools handle high-frequency and interactive workflows.

One additional Managed Auth helper (`begin_auth_login`) is marked app-only (`_meta.ui.visibility: ["app"]`); it refuses to execute on hosts that do not declare MCP Apps support. The App itself polls the shared, baseline-guarded `manage_auth_connections` `wait` action for status.

Self-hosted deployments can hide sensitive tool families by setting `KERNEL_MCP_DISABLED_TOOLSETS` to a comma-separated list. For example, `KERNEL_MCP_DISABLED_TOOLSETS=api_keys` prevents `manage_api_keys` from being registered.

Expand All @@ -272,7 +274,7 @@ Self-hosted deployments can hide sensitive tool families by setting `KERNEL_MCP_
- `manage_replays` - Start, stop, and list MP4 video replay recordings for a browser session. Session-scoped: start once, run your automation, then stop. Requires a paid Kernel plan.
- `manage_extensions` - List and delete uploaded browser extensions.
- `manage_apps` - List/search apps, invoke actions, get/list/delete deployments, and get invocation results.
- `manage_auth_connections` - Create, list, get, delete managed auth connections; start login flows (returns a hosted URL and live view); submit MFA codes or SSO selections.
- `manage_auth_connections` - Create, list, get, delete, login, submit, and wait for managed-auth connections in every client. Use domain-filtered `list` for discovery. App-capable clients additionally receive `open_auth_login`; the programmatic actions remain available there too.
- `manage_credentials` - Create, list, get, update, and delete stored credentials; fetch a current TOTP code for credentials with a configured totp_secret.
- `manage_credential_providers` - Create, list, get, update, and delete external credential providers (e.g. 1Password); list available items and test the provider connection.

Expand All @@ -283,6 +285,7 @@ Self-hosted deployments can hide sensitive tool families by setting `KERNEL_MCP_
- `execute_playwright_code` - Execute Playwright/TypeScript code against an existing browser session. Does not create or delete browsers - use `manage_browsers` for session lifecycle.
- `exec_command` - Run shell commands inside a browser VM. Returns decoded stdout/stderr.
- `search_docs` - Search Kernel platform documentation and guides.
- `open_auth_login` - Open a secure interactive Managed Auth MCP App after user consent. Registered only for clients that declare MCP Apps support; credentials and MFA never enter MCP/model traffic.

## Resources

Expand Down Expand Up @@ -327,6 +330,19 @@ Assistant: I'll create a browser session, then execute Playwright code against i
Returns: { success: true, result: "Example Domain" }
```

### Use managed authentication for a protected site

1. Call `manage_auth_connections` with `action: "list"` and the exact `domain_filter`.
2. Fetch all pages. Reuse an authenticated connection; ask only when multiple relevant accounts match.
3. A direct request to log in is consent. If authentication is discovered incidentally, ask before opening the App.
4. For a new connection, choose a concise service-derived profile name unless the user supplied one; do not ask solely for a profile name.
5. Call `open_auth_login`, then immediately follow its `next_action` and repeat the read-only wait while it reports `pending`.
6. The user enters credentials/MFA only in the secure App. Once the wait reports `authenticated`, resume the original task with the verified `profile_name`.

Example: “Log me into my Hacker News account and update my profile to add a random emoji at the bottom.” The agent should discover `news.ycombinator.com`, open the App when needed, wait for authentication, then continue the profile edit without asking for credentials or a profile name in chat.

The secure App defaults `record_session` and `browser_telemetry.enabled` to `true`, recording replay video plus the operational telemetry categories (`control`, `connection`, `system`, and `captcha`) for managed-auth browser sessions. Callers can explicitly disable either setting. The programmatic `manage_auth_connections` create/login actions preserve the API’s opt-in and inheritance behavior when these parameters are omitted.

### Set up browser profiles for authentication

```
Expand Down
14 changes: 12 additions & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@
},
"scripts": {
"dev": "next dev -p 3002",
"build": "next build",
"build:managed-auth-app": "bun scripts/build-managed-auth-app.mjs",
"check:managed-auth-app": "bun scripts/build-managed-auth-app.mjs --check",
"build": "bun run build:managed-auth-app && next build",
"start": "next start -p 3002",
"lint": "next lint",
"test": "bun test",
"format": "prettier --write \"**/*.{ts,js,json,md}\"",
"format:check": "prettier --check \"**/*.{ts,js,json,md}\""
},
Expand All @@ -34,7 +37,8 @@
"@clerk/themes": "^2.4.19",
"@mcp-ui/server": "^5.10.0",
"@modelcontextprotocol/sdk": "1.26.0",
"@onkernel/sdk": "^0.78.0",
"@onkernel/managed-auth-react": "0.4.1",
"@onkernel/sdk": "^0.85.0",
"@posthog/mcp": "0.10.1",
"@types/jsonwebtoken": "^9.0.10",
"@types/redis": "^4.0.11",
Expand All @@ -57,6 +61,7 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.11",
"@types/bun": "^1.3.14",
"@types/jszip": "^3.4.1",
"@types/node": "^20",
"@types/react": "^19",
Expand Down
90 changes: 90 additions & 0 deletions scripts/build-managed-auth-app.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Builds the managed-auth MCP App into a single self-contained HTML bundle.
// The --check mode is byte-exact, and Bun's minifier output can change between
// releases, so the bundle is only reproducible with the Bun version pinned in
// .github/workflows/ci.yml (currently 1.3.3). Regenerate the bundle with that
// exact version: bun run build:managed-auth-app
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

const root = resolve(import.meta.dirname, "..");
const entrypoint = join(root, "src/lib/mcp/apps/managed-auth-entry.tsx");
const generatedPath = join(
root,
"src/lib/mcp/apps/generated/managed-auth-app.ts",
);
const check = process.argv.includes("--check");
const temp = await mkdtemp(join(tmpdir(), "kernel-managed-auth-app-"));

try {
const build = await Bun.build({
entrypoints: [entrypoint],
outdir: temp,
target: "browser",
format: "esm",
minify: true,
splitting: false,
sourcemap: "none",
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
},
});

if (!build.success) {
for (const log of build.logs) console.error(log);
process.exitCode = 1;
} else {
let javascript = "";
let css = "";
for (const output of build.outputs) {
if (output.path.endsWith(".js")) javascript += await output.text();
if (output.path.endsWith(".css")) css += await output.text();
}
if (!javascript)
throw new Error("Bun did not emit managed-auth JavaScript");

const escapeScript = (value) => value.replaceAll("</script", "<\\/script");
const escapeStyle = (value) => value.replaceAll("</style", "<\\/style");
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Kernel Managed Authentication</title>
<style>${escapeStyle(css)}
html,body,#root{margin:0;min-height:100%}
html,body{background:transparent}
.kernel-app-status,.kernel-app-fallback{font-family:ui-sans-serif,system-ui,sans-serif;padding:16px;text-align:center}
.kernel-app-actions{display:flex;flex-direction:column;align-items:center;gap:8px;padding:0 16px 16px}
.kernel-app-button{appearance:none;border:0;border-radius:8px;background:#81b300;color:#fff;cursor:pointer;font:600 14px ui-sans-serif,system-ui,sans-serif;padding:10px 16px}
.kernel-app-button:hover{background:#709c00}
</style>
</head>
<body><div id="root"></div>
<script type="module">${escapeScript(javascript)}</script>
</body>
</html>`;
const generated = `// Generated by scripts/build-managed-auth-app.mjs. Do not edit.\nexport const MANAGED_AUTH_APP_HTML = ${JSON.stringify(html)};\n`;

if (check) {
let current = "";
try {
current = await readFile(generatedPath, "utf8");
} catch {
// Report the same actionable stale-bundle error below.
}
if (current !== generated) {
console.error(
"Managed-auth App bundle is stale. Run: bun run build:managed-auth-app",
);
process.exitCode = 1;
}
} else {
await mkdir(resolve(generatedPath, ".."), { recursive: true });
await writeFile(generatedPath, generated);
console.log(`Generated ${generatedPath}`);
}
}
} finally {
await rm(temp, { recursive: true, force: true });
}
87 changes: 84 additions & 3 deletions src/app/[transport]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,71 @@ import {
mintMcpSessionId,
} from "@/lib/mcp/analytics";
import { registerMcpCapabilities } from "@/lib/mcp/register";
import { initializeDeclaresMcpApps } from "@/lib/mcp/tools/auth-login-app";
import {
clearMcpAppsClient,
hasMcpAppsClient,
markMcpAppsClient,
} from "@/lib/redis";

// The streamable-HTTP transport creates one McpServer per request, so the
// initialize capability is unavailable when tools/list or an App call arrives.
// Persist the negotiation marker, then select the additive App registration
// only for requests that need to discover or invoke it.
async function requestUsesMcpApps(
req: NextRequest,
token: string,
ttlSeconds: number,
): Promise<boolean> {
if (req.method !== "POST") return false;
let body: unknown;
try {
body = await req.clone().json();
} catch {
return false;
}

const request =
body && typeof body === "object" && !Array.isArray(body)
? (body as {
method?: unknown;
params?: { name?: unknown; uri?: unknown };
})
: null;
if (request?.method === "initialize") {
const declaresApps = initializeDeclaresMcpApps(body);
try {
if (declaresApps) {
await markMcpAppsClient({ token, ttlSeconds });
} else {
await clearMcpAppsClient(token);
}
} catch (error) {
// Never block initialize; without a marker, later App discovery and
// invocation fail closed to the base tool set.
console.error("Failed to record MCP Apps capability:", error);
}
return false;
Comment thread
rgarcia marked this conversation as resolved.
}

const needsAppRegistration =
request?.method === "tools/list" ||
request?.method === "resources/list" ||
(request?.method === "resources/read" &&
typeof request.params?.uri === "string" &&
request.params.uri.startsWith("ui://kernel/managed-auth-login")) ||
(request?.method === "tools/call" &&
(request.params?.name === "open_auth_login" ||
request.params?.name === "begin_auth_login"));
if (!needsAppRegistration) return false;

try {
return await hasMcpAppsClient({ token, ttlSeconds });
} catch (error) {
console.error("MCP Apps capability check failed; using base tools:", error);
return false;
}
Comment thread
rgarcia marked this conversation as resolved.
}

export async function OPTIONS(_req: NextRequest): Promise<Response> {
return new Response(null, {
Expand Down Expand Up @@ -48,11 +113,16 @@ function createAuthErrorResponse(
);
}

// Create MCP handler with tools
// The base tool set is unchanged. Capability negotiation only adds the
// Managed Auth launcher, its resource, and its app-only implementation tools.
const handler = createMcpHandler((server) => {
instrumentMcpAnalytics(server);
registerMcpCapabilities(server);
});
const mcpAppsHandler = createMcpHandler((server) => {
instrumentMcpAnalytics(server);
registerMcpCapabilities(server, { mcpApps: true });
});

async function handleAuthenticatedRequest(req: NextRequest): Promise<Response> {
const authHeader = req.headers.get("Authorization");
Expand All @@ -67,8 +137,13 @@ async function handleAuthenticatedRequest(req: NextRequest): Promise<Response> {
}

if (!isValidJwtFormat(token)) {
// Opaque API keys are authenticated by the Kernel API rather than Clerk.
// Select the additive App handler from their token-bound marker here.
const selectedHandler = (await requestUsesMcpApps(req, token, 24 * 60 * 60))
? mcpAppsHandler
: handler;
const authHandler = withMcpAuth(
handler,
selectedHandler,
async () => ({
token,
scopes: ["apikey"],
Expand All @@ -95,9 +170,15 @@ async function handleAuthenticatedRequest(req: NextRequest): Promise<Response> {
);
}

// JWT markers are keyed by the decoded sid, so only read or mutate them
// after Clerk has verified the token and its expiry.
const selectedHandler = (await requestUsesMcpApps(req, token, 24 * 60 * 60))
? mcpAppsHandler
: handler;

// Create authenticated handler with auth info
const authHandler = withMcpAuth(
handler,
selectedHandler,
async (_req, _providedToken) => {
// Return auth info with validated user data
return {
Expand Down
Loading
Loading