Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 14 additions & 0 deletions docs/native-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ On every request the server:
is still authorized by the API.
- **Requests and streams** end when the exchanged token expires (at most five
minutes); clients reconnect with a fresh request.
- **Permissions** are chosen by the person who connects, on the authorization
server's consent page. The protected-resource metadata lists no
`scopes_supported`, so clients request no scopes and that page decides.
When the exchanged token names actions, toolsets none of them can use are
left out of the tool list and `get_connection_context` reports them under
`granted`. A token that names no action lists every toolset. Either way the
API authorizes each call.
- API key and workload identity tools are never listed for a token that
names actions: a sign-in cannot hold those permissions.
- The vault and search tools also depend on the organization's entitlements,
which the server reads with the connection's own token. Without
`organizations:read` (on the consent page, "view plan entitlements and
limits") that read is refused and both toolsets are left out, whatever
else was granted.

## Configuration

Expand Down
58 changes: 58 additions & 0 deletions src/app/[transport]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,64 @@ describe("native OAuth credentials", () => {
expect(issuer.requests).toHaveLength(2);
});

// The JSON a get_connection_context call returned.
async function connectionContext(response: Response) {
expect(response.status).toBe(200);
const text = await response.text();
const event = text.split("\n").find((line) => line.startsWith("data: "));
const message = JSON.parse(event ? event.slice(6) : text);
return JSON.parse(message.result.content[0].text);
}

test("list only the toolsets the token's actions can use", async () => {
issuer.respondWith({ projects: ["proj_a", "proj_b"] });
const limited = await issuer.parent({
scope: "openid browsers:use profiles:read",
});
let response = await POST(mcpRequest(limited));
expect(response.status).toBe(200);
const listed = await response.text();
for (const tool of [
"manage_browsers",
"computer_action",
"manage_profiles",
])
expect(listed).toContain(`"name":"${tool}"`);
for (const tool of ["manage_proxies", "manage_api_keys", "manage_apps"])
expect(listed).not.toContain(`"name":"${tool}"`);

response = await POST(
mcpRequest(limited, "tools/call", {
name: "get_connection_context",
arguments: {},
}),
);
expect((await connectionContext(response)).granted).toEqual({
permissions: ["browsers:use", "profiles:read"],
projects: ["proj_a", "proj_b"],
});

// A token that names no action holds its whole grant; nothing is hidden.
issuer.respondWith({});
response = await POST(mcpRequest(await refreshed()));
const everything = await response.text();
expect(everything).toContain('"name":"manage_proxies"');
expect(everything).toContain('"name":"manage_api_keys"');
});

test("report granted projects for a token that names no action", async () => {
issuer.respondWith({ projects: ["proj_a"] });
const response = await POST(
mcpRequest(await refreshed(), "tools/call", {
name: "get_connection_context",
arguments: {},
}),
);
expect((await connectionContext(response)).granted).toEqual({
projects: ["proj_a"],
});
});

test("reuse the entitlements snapshot across rotated tokens", async () => {
for (let n = 0; n < 2; n++) {
const response = await POST(mcpRequest(await refreshed()));
Expand Down
16 changes: 15 additions & 1 deletion src/app/[transport]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,18 @@ const handler = createMcpHandler(({ authInfo }) => {
mcpApps: authInfo?.extra?.mcpApps === true,
vaults: authInfo?.extra?.vaults === true,
search: authInfo?.extra?.search === true,
permissions: authInfo?.extra?.permissions as string[] | undefined,
});
return server;
});

type AuthInfoExtra = {
userId: string | null;
clerkToken: string | null;
// The actions a Kernel-issued credential names and, when its grant is
// limited to some, the projects it may use.
permissions?: string[];
projects?: string[];
};

// A refused connection never reaches the instrumented server, so this
Expand Down Expand Up @@ -342,6 +347,10 @@ async function handleAuthenticatedRequest(
if (native.status !== "ok")
return refuseConnection(req, "authentication", "native_oauth", native);
const { credential } = native;
// Action scopes name a resource kind and a verb; identity scopes do not.
// A token that names no action holds its whole grant, which it does not
// list, so nothing is known about what it may do.
const actions = credential.scopes.filter((scope) => scope.includes(":"));
// The exchanged token rotates; identity is the verified subject, and the
// request ends when the exchanged token does, streams included.
return await handleMcpRequestWithIdentity({
Expand All @@ -357,7 +366,12 @@ async function handleAuthenticatedRequest(
userId: credential.subject,
}),
scopes: credential.scopes,
authInfoExtra: { userId: credential.subject, clerkToken: null },
authInfoExtra: {
userId: credential.subject,
clerkToken: null,
permissions: actions.length > 0 ? actions : undefined,
projects: credential.projects,
},
credentialType: "native_oauth",
transportSessionId,
entitlementsCacheCredential: credential.grantId,
Expand Down
77 changes: 77 additions & 0 deletions src/lib/mcp/register.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,83 @@ describe("MCP toolset allowlist", () => {
});
});

describe("MCP toolsets by granted permission", () => {
async function toolsFor(permissions?: string[]) {
const mcp = await connectTestMcp((server) => {
registerMcpCapabilities(server, {
mcpApps: true,
vaults: true,
search: true,
permissions,
});
}, {});
try {
return (await mcp.client.listTools()).tools.map((tool) => tool.name);
} finally {
await mcp.close();
}
}

test("lists everything when the credential names no action", async () => {
expect(await toolsFor()).toEqual(
expect.arrayContaining([
"manage_browsers",
"manage_api_keys",
"manage_workload_identity",
"manage_tasks",
"manage_proxies",
"manage_vaults",
"web_search",
"open_auth_login",
]),
);
});

test("leaves out toolsets no granted action can use", async () => {
const tools = await toolsFor([
"browsers:use",
"profiles:read",
"invocations:read",
]);
expect(tools).toEqual(
expect.arrayContaining([
"get_connection_context",
"search_docs",
"manage_browsers",
"computer_action",
"execute_playwright_code",
"manage_replays",
"manage_profiles",
"manage_apps",
]),
);
for (const hidden of [
"manage_api_keys",
"manage_workload_identity",
"manage_tasks",
"manage_proxies",
"manage_vaults",
"manage_credentials",
"manage_auth_connections",
"open_auth_login",
"web_search",
])
expect(tools).not.toContain(hidden);
});

test("lists the task tools for a task action", async () => {
expect(await toolsFor(["tasks:read"])).toContain("manage_tasks");
});

test("an entitled toolset still needs a granted action", async () => {
expect(await toolsFor(["vaults:read"])).toContain("manage_vaults");
expect(await toolsFor(["searches:read"])).toContain("web_search");
expect(await toolsFor(["auth_connections:use"])).toEqual(
expect.arrayContaining(["manage_auth_connections", "open_auth_login"]),
);
});
});

describe("project selection registration", () => {
const projectScopedTools = [
"manage_profiles",
Expand Down
77 changes: 75 additions & 2 deletions src/lib/mcp/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ type McpRegistrationOptions = {
mcpApps?: boolean;
vaults?: boolean;
search?: boolean;
// The actions a Kernel-issued credential names. Toolsets it cannot use at
// all are left out. Undefined means the credential names none (an API key,
// or a token that holds its whole grant), and every toolset is listed.
permissions?: readonly string[];
dependencies?: McpDependencies;
};
type RegisterMcpToolset = (server: McpServer, options: McpToolOptions) => void;
Expand Down Expand Up @@ -74,6 +78,72 @@ const mcpToolRegistrations = [

type McpToolset = (typeof mcpToolRegistrations)[number][0];

// The KERNEL API resource kinds the toolsets act on; an action is named
// "<kind>:<verb>".
type McpResourceKind =
| "auth_connections"
| "browser_pools"
| "browsers"
| "config_registry"
| "credential_providers"
| "credentials"
| "deployments"
| "extensions"
| "invocations"
| "profiles"
| "projects"
| "proxies"
| "searches"
| "tasks"
| "vault_provider_configs"
| "vaults";

// What a credential that names its actions needs for each toolset to be
// listed: any action on one of the listed resource kinds, nothing ("any"), or
// a permission no such credential can hold ("never"). The API still
// authorizes every call.
const mcpToolsetRequirements: Record<
McpToolset,
readonly McpResourceKind[] | "any" | "never"
> = {
profiles: ["profiles"],
tasks: ["tasks"],
docs: "any",
browsers: ["browsers"],
projects: ["projects"],
api_keys: "never",
workload_identity: "never",
browser_pools: ["browser_pools"],
config_registry: ["config_registry"],
browser_curl: ["browsers"],
browser_files: ["browsers"],
proxies: ["proxies"],
extensions: ["extensions"],
apps: ["deployments", "invocations"],
computer: ["browsers"],
shell: ["browsers"],
playwright: ["browsers"],
repl: ["browsers"],
webmcp: ["browsers"],
replays: ["browsers"],
auth_connections: ["auth_connections"],
credentials: ["credentials"],
credential_providers: ["credential_providers"],
vaults: ["vaults", "vault_provider_configs"],
search: ["searches"],
};

function toolsetPermitted(
permissions: readonly string[] | undefined,
toolset: McpToolset,
) {
const required = mcpToolsetRequirements[toolset];
if (permissions === undefined || required === "any") return true;
if (required === "never") return false;
const kinds: readonly string[] = required;
return permissions.some((action) => kinds.includes(action.split(":")[0]));
}

const mcpToolsets = mcpToolRegistrations.map(([toolset]) => toolset);
const mcpToolsetSet: ReadonlySet<string> = new Set(mcpToolsets);

Expand Down Expand Up @@ -200,6 +270,7 @@ export function registerMcpCapabilities(
mcpApps = false,
vaults = false,
search = false,
permissions,
dependencies = defaultMcpDependencies,
}: McpRegistrationOptions = {},
) {
Expand All @@ -215,7 +286,8 @@ export function registerMcpCapabilities(
if (
(toolset !== "vaults" || vaults) &&
(toolset !== "search" || search) &&
toolsetEnabled(enabledToolsets, disabledToolsets, toolset)
toolsetEnabled(enabledToolsets, disabledToolsets, toolset) &&
toolsetPermitted(permissions, toolset)
) {
registerToolset(server, dependencies);
}
Expand All @@ -226,7 +298,8 @@ export function registerMcpCapabilities(
// resource) without replacing or narrowing manage_auth_connections.
if (
mcpApps &&
toolsetEnabled(enabledToolsets, disabledToolsets, "auth_connections")
toolsetEnabled(enabledToolsets, disabledToolsets, "auth_connections") &&
toolsetPermitted(permissions, "auth_connections")
) {
registerAuthLoginApp(server);
}
Expand Down
6 changes: 5 additions & 1 deletion src/lib/mcp/tools/connection-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function registerConnectionContextTool(server: McpServer) {
"get_connection_context",
{
description:
"inspect the authenticated KERNEL principal, organization, credential and effective scope, and current effective policy before an operation. service-account principals may also include sanitized workload_identity provenance; no credential secrets or original identity-provider claims are returned. connection_scope.kind=organization may omit project for organization-wide reads and default-project creates, or pass a project name or id. connection_scope.kind=project is fixed to connection_scope.project_id.",
"inspect the authenticated KERNEL principal, organization, credential and effective scope, and current effective policy before an operation. service-account principals may also include sanitized workload_identity provenance; no credential secrets or original identity-provider claims are returned. connection_scope.kind=organization may omit project for organization-wide reads and default-project creates, or pass a project name or id. connection_scope.kind=project is fixed to connection_scope.project_id. when the person who connected chose what this connection may do, granted.permissions lists the allowed actions and granted.projects the only projects it may use (absent means every project); with one granted project, omit project to use it: KERNEL runs a request that names no project in that project.",
inputSchema: z.object({}),
annotations: {
title: "get KERNEL connection context",
Expand All @@ -23,8 +23,12 @@ export function registerConnectionContextTool(server: McpServer) {
const { authContext, scope } = connectionContextFromAuthInfo(
ctx.http.authInfo,
);
const { permissions, projects } = ctx.http.authInfo.extra ?? {};
return jsonResponse({
...authContext,
...((permissions !== undefined || projects !== undefined) && {
granted: { permissions, projects },
}),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
connection_scope: {
kind: scope.kind,
organization_id: scope.organizationId,
Expand Down
Loading
Loading