From f36c706081b4231b90a766553d6ac1e9d2e91143 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:03:17 +0000 Subject: [PATCH 1/5] feat(appkit): serve selected tools over MCP Signed-off-by: mario.cadenas Co-authored-by: Isaac --- NOTICE.md | 2 + docs/docs/api/appkit/Function.mcp.md | 15 + .../api/appkit/Interface.BasePluginConfig.md | 1 + .../docs/api/appkit/Interface.FunctionTool.md | 20 ++ .../api/appkit/Interface.McpPluginConfig.md | 100 ++++++ docs/docs/api/appkit/Interface.ToolConfig.md | 20 ++ .../api/appkit/Interface.ToolkitOptions.md | 10 + docs/docs/api/appkit/index.md | 2 + docs/docs/api/appkit/typedoc-sidebar.ts | 10 + docs/docs/plugins/mcp.md | 107 +++++++ packages/appkit/package.json | 14 +- packages/appkit/src/beta.ts | 2 + packages/appkit/src/core/agent/scope-error.ts | 6 + .../src/core/agent/tools/function-tool.ts | 4 + packages/appkit/src/core/agent/tools/tool.ts | 6 + packages/appkit/src/core/agent/types.ts | 2 + .../src/plugins/agents/tool-dispatch.ts | 9 +- .../src/plugins/beta-exports.generated.ts | 1 + packages/appkit/src/plugins/mcp/http.ts | 66 ++++ packages/appkit/src/plugins/mcp/index.ts | 2 + packages/appkit/src/plugins/mcp/manifest.json | 8 + packages/appkit/src/plugins/mcp/mcp.ts | 85 ++++++ .../appkit/src/plugins/mcp/tests/mcp.test.ts | 285 ++++++++++++++++++ .../src/plugins/mcp/tests/tools.test.ts | 231 ++++++++++++++ packages/appkit/src/plugins/mcp/tools.ts | 241 +++++++++++++++ packages/appkit/src/plugins/mcp/types.ts | 10 + pnpm-lock.yaml | 51 ++++ template/appkit.plugins.json | 11 + 28 files changed, 1309 insertions(+), 12 deletions(-) create mode 100644 docs/docs/api/appkit/Function.mcp.md create mode 100644 docs/docs/api/appkit/Interface.McpPluginConfig.md create mode 100644 docs/docs/plugins/mcp.md create mode 100644 packages/appkit/src/core/agent/scope-error.ts create mode 100644 packages/appkit/src/plugins/mcp/http.ts create mode 100644 packages/appkit/src/plugins/mcp/index.ts create mode 100644 packages/appkit/src/plugins/mcp/manifest.json create mode 100644 packages/appkit/src/plugins/mcp/mcp.ts create mode 100644 packages/appkit/src/plugins/mcp/tests/mcp.test.ts create mode 100644 packages/appkit/src/plugins/mcp/tests/tools.test.ts create mode 100644 packages/appkit/src/plugins/mcp/tools.ts create mode 100644 packages/appkit/src/plugins/mcp/types.ts diff --git a/NOTICE.md b/NOTICE.md index 3c8788304..f4259c3ef 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -8,6 +8,8 @@ This Software contains code from the following open source projects: | :--------------- | :---------------- | :----------- | :--------------------------------------------------- | | [@ast-grep/napi](https://www.npmjs.com/package/@ast-grep/napi) | 0.37.0 | MIT | https://ast-grep.github.io | | [@clack/prompts](https://www.npmjs.com/package/@clack/prompts) | 1.0.1 | MIT | https://github.com/bombshell-dev/clack/tree/main/packages/prompts#readme | +| [@modelcontextprotocol/node](https://www.npmjs.com/package/@modelcontextprotocol/node) | 2.1.2 | Apache-2.0 | https://modelcontextprotocol.io | +| [@modelcontextprotocol/server](https://www.npmjs.com/package/@modelcontextprotocol/server) | 2.4.0 | Apache-2.0 | https://modelcontextprotocol.io | | [@opentelemetry/api](https://www.npmjs.com/package/@opentelemetry/api) | 1.9.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/api | | [@opentelemetry/api-logs](https://www.npmjs.com/package/@opentelemetry/api-logs) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/api-logs | | [@opentelemetry/auto-instrumentations-node](https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node) | 0.81.2 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/auto-instrumentations-node#readme | diff --git a/docs/docs/api/appkit/Function.mcp.md b/docs/docs/api/appkit/Function.mcp.md new file mode 100644 index 000000000..50b648ed9 --- /dev/null +++ b/docs/docs/api/appkit/Function.mcp.md @@ -0,0 +1,15 @@ +# Function: mcp() + +```ts +function mcp(config: McpPluginConfig): PluginData; +``` + +## Parameters + +| Parameter | Type | +| ------ | ------ | +| `config` | [`McpPluginConfig`](Interface.McpPluginConfig.md) | + +## Returns + +[`PluginData`](TypeAlias.PluginData.md)\<*typeof* `McpPlugin`, [`BasePluginConfig`](Interface.BasePluginConfig.md), `"mcp"`\> diff --git a/docs/docs/api/appkit/Interface.BasePluginConfig.md b/docs/docs/api/appkit/Interface.BasePluginConfig.md index 9ee98474b..a4f94ee58 100644 --- a/docs/docs/api/appkit/Interface.BasePluginConfig.md +++ b/docs/docs/api/appkit/Interface.BasePluginConfig.md @@ -6,6 +6,7 @@ Base configuration interface for AppKit plugins - [`AgentsPluginConfig`](Interface.AgentsPluginConfig.md) - [`IAiSearchConfig`](Interface.IAiSearchConfig.md) +- [`McpPluginConfig`](Interface.McpPluginConfig.md) - [`IJobsConfig`](Interface.IJobsConfig.md) ## Indexable diff --git a/docs/docs/api/appkit/Interface.FunctionTool.md b/docs/docs/api/appkit/Interface.FunctionTool.md index 450db5385..38be404ec 100644 --- a/docs/docs/api/appkit/Interface.FunctionTool.md +++ b/docs/docs/api/appkit/Interface.FunctionTool.md @@ -68,6 +68,26 @@ optional parameters: Record | null; *** +### runAs? + +```ts +optional runAs: "user" | "app"; +``` + +Honoured by mcp() only; agents use their own identity. + +*** + +### scopes? + +```ts +optional scopes: string[]; +``` + +Honoured by mcp() only. + +*** + ### strict? ```ts diff --git a/docs/docs/api/appkit/Interface.McpPluginConfig.md b/docs/docs/api/appkit/Interface.McpPluginConfig.md new file mode 100644 index 000000000..dbe8b820f --- /dev/null +++ b/docs/docs/api/appkit/Interface.McpPluginConfig.md @@ -0,0 +1,100 @@ +# Interface: McpPluginConfig + +Base configuration interface for AppKit plugins + +## Extends + +- [`BasePluginConfig`](Interface.BasePluginConfig.md) + +## Indexable + +```ts +[key: string]: unknown +``` + +## Properties + +### allowedOrigins? + +```ts +optional allowedOrigins: string[]; +``` + +*** + +### description? + +```ts +optional description: string; +``` + +*** + +### host? + +```ts +optional host: string; +``` + +#### Inherited from + +[`BasePluginConfig`](Interface.BasePluginConfig.md).[`host`](Interface.BasePluginConfig.md#host) + +*** + +### name + +```ts +name: string; +``` + +#### Overrides + +[`BasePluginConfig`](Interface.BasePluginConfig.md).[`name`](Interface.BasePluginConfig.md#name) + +*** + +### streamConfig? + +```ts +optional streamConfig: StreamConfig; +``` + +SSE stream configuration for this plugin's `executeStream()` calls (buffer +sizes, `maxEventSize`, TTL, heartbeat). Sets the plugin's StreamManager +defaults; a per-call `stream` config still overrides these. Use it to raise +`maxEventSize` above the 5 MiB default when a stream emits larger events. + +#### Inherited from + +[`BasePluginConfig`](Interface.BasePluginConfig.md).[`streamConfig`](Interface.BasePluginConfig.md#streamconfig) + +*** + +### telemetry? + +```ts +optional telemetry: TelemetryOptions; +``` + +#### Inherited from + +[`BasePluginConfig`](Interface.BasePluginConfig.md).[`telemetry`](Interface.BasePluginConfig.md#telemetry) + +*** + +### tools() + +```ts +tools: (plugins: Plugins) => AgentTools; +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `plugins` | [`Plugins`](TypeAlias.Plugins.md) | + +#### Returns + +[`AgentTools`](TypeAlias.AgentTools.md) diff --git a/docs/docs/api/appkit/Interface.ToolConfig.md b/docs/docs/api/appkit/Interface.ToolConfig.md index bd35155a1..c4c6b884e 100644 --- a/docs/docs/api/appkit/Interface.ToolConfig.md +++ b/docs/docs/api/appkit/Interface.ToolConfig.md @@ -83,8 +83,28 @@ outside any keyed-record context — otherwise the record key wins. *** +### runAs? + +```ts +optional runAs: "user" | "app"; +``` + +Honoured by mcp() only; agents use their own identity. + +*** + ### schema ```ts schema: S; ``` + +*** + +### scopes? + +```ts +optional scopes: string[]; +``` + +User API scopes required when served by mcp(); ignored by agents. diff --git a/docs/docs/api/appkit/Interface.ToolkitOptions.md b/docs/docs/api/appkit/Interface.ToolkitOptions.md index 1beb22b0f..eaa824332 100644 --- a/docs/docs/api/appkit/Interface.ToolkitOptions.md +++ b/docs/docs/api/appkit/Interface.ToolkitOptions.md @@ -39,3 +39,13 @@ optional rename: Record; ``` Remap specific local names to different keys (applied after prefix). + +*** + +### runAs? + +```ts +optional runAs: "user" | "app"; +``` + +Honoured by mcp() only; agents use their own identity. diff --git a/docs/docs/api/appkit/index.md b/docs/docs/api/appkit/index.md index 90f64e67c..d8318b696 100644 --- a/docs/docs/api/appkit/index.md +++ b/docs/docs/api/appkit/index.md @@ -94,6 +94,7 @@ surface with `@databricks/appkit/beta`. Not meant for application imports. | [LakebasePoolManager](Interface.LakebasePoolManager.md) | Manages multiple Lakebase connection pools keyed by an identifier (e.g. userId). | | [MatchResult](Interface.MatchResult.md) | Result of a deterministic matcher run against a value. | | [McpConnectAllResult](Interface.McpConnectAllResult.md) | Per-endpoint outcome of [AppKitMcpClient.connectAll](Class.AppKitMcpClient.md#connectall). Callers (the agents plugin in particular) use the split to warn at startup when some MCP servers are unreachable without aborting boot for the rest. | +| [McpPluginConfig](Interface.McpPluginConfig.md) | Base configuration interface for AppKit plugins | | [Message](Interface.Message.md) | - | | [OperationContext](Interface.OperationContext.md) | What `allow` and `execute` receive: the policy context and the loaded resource. | | [OperationDefinition](Interface.OperationDefinition.md) | One immutable operation descriptor. Nothing in it runs until a request does. | @@ -275,6 +276,7 @@ surface with `@databricks/appkit/beta`. Not meant for application imports. | [loadAgentsFromDir](Function.loadAgentsFromDir.md) | Scans a directory for one subdirectory per agent, each containing `agent.md` (frontmatter + body). Produces an `AgentDefinition` record keyed by agent id (folder name). Throws on frontmatter errors or unresolved references. Returns an empty map if the directory does not exist. | | [loadRootEvalConfig](Function.loadRootEvalConfig.md) | Load the root `evals.config.ts` under `rootDir` (the project root), or return `undefined` when there is none. This is the run-wide config carrying `baseUrl`/`webServer`; the CLI reads it to resolve options and manage the app-under-test lifecycle before calling [runEvalsInDir](Function.runEvalsInDir.md). | | [matches](Function.matches.md) | Passes when the value matches `pattern`. | +| [mcp](Function.mcp.md) | - | | [mcpServer](Function.mcpServer.md) | Factory for declaring a custom MCP server tool. | | [normalizeHost](Function.normalizeHost.md) | Ensure the host has a scheme (Databricks env often lacks `https://`). | | [parseTextToolCalls](Function.parseTextToolCalls.md) | Parses text-based tool calls from model output. | diff --git a/docs/docs/api/appkit/typedoc-sidebar.ts b/docs/docs/api/appkit/typedoc-sidebar.ts index 3ae41a018..f9f0c93aa 100644 --- a/docs/docs/api/appkit/typedoc-sidebar.ts +++ b/docs/docs/api/appkit/typedoc-sidebar.ts @@ -404,6 +404,11 @@ const typedocSidebar: SidebarsConfig = { id: "api/appkit/Interface.McpConnectAllResult", label: "McpConnectAllResult" }, + { + type: "doc", + id: "api/appkit/Interface.McpPluginConfig", + label: "McpPluginConfig" + }, { type: "doc", id: "api/appkit/Interface.Message", @@ -1256,6 +1261,11 @@ const typedocSidebar: SidebarsConfig = { id: "api/appkit/Function.matches", label: "matches" }, + { + type: "doc", + id: "api/appkit/Function.mcp", + label: "mcp" + }, { type: "doc", id: "api/appkit/Function.mcpServer", diff --git a/docs/docs/plugins/mcp.md b/docs/docs/plugins/mcp.md new file mode 100644 index 000000000..3e357a921 --- /dev/null +++ b/docs/docs/plugins/mcp.md @@ -0,0 +1,107 @@ +--- +sidebar_position: 18 +--- + +# MCP server plugin + + +:::warning Beta plugin +This plugin is currently **beta**. APIs may change between minor releases. Import from `@databricks/appkit/beta`. See [Plugin Stability Tiers](./stability.md). +::: + + +The beta MCP plugin serves selected AppKit tools on `/mcp` using stateless +streamable HTTP. Register the App as a Unity Catalog MCP Service behind Unity +Gateway. + +:::danger Governance +Calls made directly to `/mcp` skip Unity Gateway's governance until blocking +direct calls exists. Restrict access to the App accordingly. +::: + +## Setup + +```ts +import { createApp, genie, server } from "@databricks/appkit"; +import { mcp, tool } from "@databricks/appkit/beta"; +import { z } from "zod"; + +await createApp({ + plugins: [ + server(), + genie({ spaces: { sales: "space-id" } }), + mcp({ + name: "sales", + description: "Sales tools", + allowedOrigins: ["https://portal.example.com"], + tools(plugins) { + return { + ...plugins.genie.toolkit({ only: ["sales.sendMessage"] }), + lookupCustomer: tool({ + description: "Look up a customer by ID", + schema: z.object({ id: z.string() }), + runAs: "user", + scopes: ["sql"], + annotations: { effect: "read" }, + execute: async ({ id }) => ({ id }), + }), + }; + }, + }), + ], +}); +``` + +The object returned by `tools(plugins)` is exactly the set served. Toolkit +entries retain their names (for example `genie.sales.sendMessage`); developer +tools use the object key. Toolkit options `only`, `except`, `prefix` and +`rename` work as they do for agents. Toolkit entries are read-only by default: +write, update, destructive, and tools without an `effect` are omitted unless +named explicitly in `only`. Developer tools are included explicitly by key. + +## Identity and scopes + +`runAs: "user"` is the default and uses the caller's forwarded token. +`runAs: "app"` executes as the App's service principal. Set it on `tool()` or +on `toolkit()`; the caller cannot choose it. App-run tools are logged with a +warning. `runAs` and `scopes` are honoured by `mcp()` only: agents sharing +these tools continue to use their own identity. + +For user-run developer tools, supply `scopes: ["sql", ...]`. User-run toolkit +scopes come from the plugin manifest and resource types. At startup AppKit logs +each tool's identity and scopes and the union to declare in the App's +`user_api_scopes`. When running in a Databricks App it also warns if the App's +effective scopes are missing any of them. A lookup failure only warns. + +Lakebase toolkit tools run as the App and add no user scopes. Explicit +`runAs: "user"` is refused at startup: no workspace test has yet confirmed +that an Apps-forwarded user token can mint a Lakebase credential, and AppKit +does not map the postgres scope. This stopgap does not affect developer tools +that query Lakebase themselves. + +## Annotations + +| AppKit effect | `readOnlyHint` | `destructiveHint` | +|---|---|---| +| `read` | `true` | omitted | +| `write` / `update` | `false` | `false` | +| `destructive` | `false` | `true` | + +Legacy `readOnly` and `destructive` flags map to their corresponding hints; +`idempotent` maps to `idempotentHint`. + +## HTTP behavior and errors + +POST supports MCP. GET and DELETE return 405. Requests without Origin are +accepted; requests with a valid same-origin host or a listed `allowedOrigins` +origin are accepted. Other, malformed, or `null` origins return 403. + +Tool failures return MCP `isError` content. Missing user tokens and recognizable +missing-scope errors identify the required `user_api_scopes`; other failures +return a fixed message and log the details. Before MCP runs, errors return +JSON-RPC error objects with the HTTP status preserved: malformed JSON is +`-32700`, 413 and other 4xx are `-32600`, 401 is `-32000`, and 5xx is +`-32603` with a fixed internal-error message. + +In development, AppKit's usual missing-token fallback runs a user tool as the +service principal with a warning. diff --git a/packages/appkit/package.json b/packages/appkit/package.json index e58d739db..8a9aa3a80 100644 --- a/packages/appkit/package.json +++ b/packages/appkit/package.json @@ -75,21 +75,23 @@ "@databricks/sdk-auth": "0.51.0", "@databricks/sdk-core": "0.51.0", "@databricks/sdk-database": "0.51.0", - "@databricks/sdk-files": "0.52.0", "@databricks/sdk-experiments": "0.52.0", + "@databricks/sdk-files": "0.52.0", "@databricks/sdk-genie": "0.54.0", - "@databricks/sdk-uc-functions": "0.51.0", "@databricks/sdk-jobs": "0.57.0", "@databricks/sdk-modelserving": "0.53.0", - "@databricks/sdk-uc-connections": "0.52.0", - "@databricks/sdk-uc-tables": "0.52.0", - "@databricks/sdk-uc-volumes": "0.51.0", - "@databricks/sdk-vectorsearch": "0.51.0", "@databricks/sdk-options": "0.51.0", "@databricks/sdk-postgres": "0.52.0", "@databricks/sdk-scim": "0.51.0", "@databricks/sdk-statementexecution": "0.52.0", + "@databricks/sdk-uc-connections": "0.52.0", + "@databricks/sdk-uc-functions": "0.51.0", + "@databricks/sdk-uc-tables": "0.52.0", + "@databricks/sdk-uc-volumes": "0.51.0", + "@databricks/sdk-vectorsearch": "0.51.0", "@databricks/sdk-warehouses": "0.53.0", + "@modelcontextprotocol/node": "2.1.2", + "@modelcontextprotocol/server": "2.4.0", "@opentelemetry/api": "1.9.0", "@opentelemetry/api-logs": "0.223.0", "@opentelemetry/auto-instrumentations-node": "0.81.2", diff --git a/packages/appkit/src/beta.ts b/packages/appkit/src/beta.ts index 71ac6a01a..df7f0ce4d 100644 --- a/packages/appkit/src/beta.ts +++ b/packages/appkit/src/beta.ts @@ -146,3 +146,5 @@ export { type PolicyDecision, type PolicyDenial, } from "./plugins/database/operations"; + +export type { McpPluginConfig } from "./plugins/mcp"; diff --git a/packages/appkit/src/core/agent/scope-error.ts b/packages/appkit/src/core/agent/scope-error.ts new file mode 100644 index 000000000..610d502af --- /dev/null +++ b/packages/appkit/src/core/agent/scope-error.ts @@ -0,0 +1,6 @@ +/** Extract the scope list from the Databricks API's missing-scope error. */ +export function getRequiredScopes(error: unknown): string | undefined { + const message = error instanceof Error ? error.message : String(error); + const match = message.match(/required scopes?:\s*([^[\]]+)/i); + return match?.[1].trim().replace(/\s+/g, " "); +} diff --git a/packages/appkit/src/core/agent/tools/function-tool.ts b/packages/appkit/src/core/agent/tools/function-tool.ts index b4e00930c..09aeee6fc 100644 --- a/packages/appkit/src/core/agent/tools/function-tool.ts +++ b/packages/appkit/src/core/agent/tools/function-tool.ts @@ -23,6 +23,10 @@ export interface FunctionTool { * tool indexes. */ annotations?: ToolAnnotations; + /** Honoured by mcp() only; agents use their own identity. */ + runAs?: "user" | "app"; + /** Honoured by mcp() only. */ + scopes?: string[]; /** * Returns any shape; downstream `normalizeToolResult` serializes to a * string before handing the value to the LLM. diff --git a/packages/appkit/src/core/agent/tools/tool.ts b/packages/appkit/src/core/agent/tools/tool.ts index 62092f217..a2ab4ed0f 100644 --- a/packages/appkit/src/core/agent/tools/tool.ts +++ b/packages/appkit/src/core/agent/tools/tool.ts @@ -38,6 +38,10 @@ export interface ToolConfig { * added this field. */ annotations?: ToolAnnotations; + /** Honoured by mcp() only; agents use their own identity. */ + runAs?: "user" | "app"; + /** User API scopes required when served by mcp(); ignored by agents. */ + scopes?: string[]; /** * Returning a non-string value is fine: the agent runtime serializes * the result via `normalizeToolResult` before handing it to the LLM @@ -74,6 +78,8 @@ export function tool(config: ToolConfig): FunctionTool { description: config.description, parameters, ...(config.annotations ? { annotations: config.annotations } : {}), + ...(config.runAs !== undefined ? { runAs: config.runAs } : {}), + ...(config.scopes !== undefined ? { scopes: config.scopes } : {}), execute: async (args: Record) => { const parsed = config.schema.safeParse(args); if (!parsed.success) { diff --git a/packages/appkit/src/core/agent/types.ts b/packages/appkit/src/core/agent/types.ts index 0fe15c043..30a4daa0c 100644 --- a/packages/appkit/src/core/agent/types.ts +++ b/packages/appkit/src/core/agent/types.ts @@ -46,6 +46,8 @@ export type AgentTool = | import("../../agents/supervisor-api").HostedSupervisorTool; export interface ToolkitOptions { + /** Honoured by mcp() only; agents use their own identity. */ + runAs?: "user" | "app"; /** Key prefix to prepend to each tool's local name. Defaults to `${pluginName}.`. */ prefix?: string; /** Only include tools whose local name matches one of these. */ diff --git a/packages/appkit/src/plugins/agents/tool-dispatch.ts b/packages/appkit/src/plugins/agents/tool-dispatch.ts index 5e34fb7b3..767633960 100644 --- a/packages/appkit/src/plugins/agents/tool-dispatch.ts +++ b/packages/appkit/src/plugins/agents/tool-dispatch.ts @@ -8,6 +8,7 @@ import { normalizeIdentityError } from "../../context/execution-context"; import { createRequestScope } from "../../context/request-scope"; import { consumeAdapterStream } from "../../core/agent/consume-adapter-stream"; import { normalizeToolResult } from "../../core/agent/normalize-result"; +import { getRequiredScopes } from "../../core/agent/scope-error"; import type { BaseSystemPromptOption, RegisteredAgent, @@ -188,12 +189,8 @@ function describeMissingOboScope( err: unknown, ): Error | undefined { if (entry.source !== "toolkit" && entry.source !== "mcp") return undefined; - const message = err instanceof Error ? err.message : String(err); - // Platform wording: "...does not have required scopes: sql" — optionally a - // comma-separated list, optionally trailed by a "[ReqId: ...]" suffix. - const match = message.match(/required scopes?:\s*([^[\]]+)/i); - if (!match) return undefined; - const scopes = match[1].trim().replace(/\s+/g, " "); + const scopes = getRequiredScopes(err); + if (scopes === undefined) return undefined; const origin = entry.source === "toolkit" ? `from the '${entry.pluginName}' plugin` diff --git a/packages/appkit/src/plugins/beta-exports.generated.ts b/packages/appkit/src/plugins/beta-exports.generated.ts index aab6fb478..80d45acc8 100644 --- a/packages/appkit/src/plugins/beta-exports.generated.ts +++ b/packages/appkit/src/plugins/beta-exports.generated.ts @@ -8,3 +8,4 @@ export { agents } from "./agents"; export { aiSearch } from "./ai-search"; export { design } from "./design"; +export { mcp } from "./mcp"; diff --git a/packages/appkit/src/plugins/mcp/http.ts b/packages/appkit/src/plugins/mcp/http.ts new file mode 100644 index 000000000..47cd7c50e --- /dev/null +++ b/packages/appkit/src/plugins/mcp/http.ts @@ -0,0 +1,66 @@ +import type { ErrorRequestHandler, RequestHandler } from "express"; + +import { AppKitError } from "../../errors/base"; +import { createLogger } from "../../logging/logger"; + +const logger = createLogger("mcp"); + +export function originGuard(allowedOrigins: string[] = []): RequestHandler { + return (req, res, next) => { + const origin = req.header("origin"); + if (origin === undefined) return next(); + let valid = false; + try { + const parsed = new URL(origin); + valid = + (parsed.protocol === "http:" || parsed.protocol === "https:") && + parsed.origin === origin && + (parsed.host === + (req.header("x-forwarded-host") ?? req.header("host")) || + allowedOrigins.includes(origin)); + } catch { + /* invalid Origin */ + } + if (valid) return next(); + res.status(403).json({ + jsonrpc: "2.0", + id: null, + error: { code: -32600, message: "Forbidden origin" }, + }); + }; +} + +export const mcpErrorHandler: ErrorRequestHandler = ( + error, + _req, + res, + next, +) => { + if (res.headersSent) return next(error); + const status = + error instanceof AppKitError + ? error.statusCode + : (error.status ?? error.statusCode ?? 500); + const code = + status === 400 && error.type === "entity.parse.failed" + ? -32700 + : status === 401 + ? -32000 + : status < 500 + ? -32600 + : -32603; + const message = + status >= 500 + ? "Internal error" + : status === 401 && error instanceof AppKitError + ? error.clientMessage + : status === 400 && code === -32700 + ? "Parse error" + : status === 413 + ? "Request too large" + : "Invalid request"; + if (status >= 500) logger.error("MCP request failed: %O", error); + res + .status(status) + .json({ jsonrpc: "2.0", id: null, error: { code, message } }); +}; diff --git a/packages/appkit/src/plugins/mcp/index.ts b/packages/appkit/src/plugins/mcp/index.ts new file mode 100644 index 000000000..176b1c3e0 --- /dev/null +++ b/packages/appkit/src/plugins/mcp/index.ts @@ -0,0 +1,2 @@ +export { mcp } from "./mcp"; +export type { McpPluginConfig } from "./types"; diff --git a/packages/appkit/src/plugins/mcp/manifest.json b/packages/appkit/src/plugins/mcp/manifest.json new file mode 100644 index 000000000..aeb8c9fbb --- /dev/null +++ b/packages/appkit/src/plugins/mcp/manifest.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://databricks.github.io/appkit/schemas/plugin-manifest.schema.json", + "name": "mcp", + "displayName": "MCP Server Plugin", + "stability": "beta", + "description": "Serve AppKit tools over MCP", + "resources": { "required": [], "optional": [] } +} diff --git a/packages/appkit/src/plugins/mcp/mcp.ts b/packages/appkit/src/plugins/mcp/mcp.ts new file mode 100644 index 000000000..fc4d28b3e --- /dev/null +++ b/packages/appkit/src/plugins/mcp/mcp.ts @@ -0,0 +1,85 @@ +import { AsyncLocalStorage } from "node:async_hooks"; + +import { toNodeHandler } from "@modelcontextprotocol/node"; +import { + createMcpHandler, + fromJsonSchema, + McpServer, +} from "@modelcontextprotocol/server"; +import type { Request, RequestHandler } from "express"; +import type { BasePluginConfig } from "shared"; + +import packageJson from "../../../package.json"; +import { Plugin, toPlugin } from "../../plugin"; +import { defineManifest } from "../../registry"; +import { mcpErrorHandler, originGuard } from "./http"; +import manifest from "./manifest.json"; +import { checkScopes, resolveTools } from "./tools"; +import type { McpPluginConfig } from "./types"; + +type InternalConfig = McpPluginConfig & { serverName: string }; +export class McpPlugin extends Plugin { + declare protected config: InternalConfig; + + constructor(config: BasePluginConfig) { + super(config); + this.config = config as InternalConfig; + } + static manifest = defineManifest<"mcp">(manifest); + static phase = "deferred" as const; + + async setup(): Promise { + if (!this.context) throw new Error("MCP plugin requires a plugin context"); + const tools = resolveTools(this.context, this.config.tools); + await checkScopes(tools); + const store = new AsyncLocalStorage(); + const descriptors = tools.map((tool) => ({ + tool, + schema: fromJsonSchema>(tool.parameters), + })); + const factory = () => { + const server = new McpServer({ + name: this.config.serverName, + version: packageJson.version, + description: this.config.description, + }); + for (const { tool, schema } of descriptors) + server.registerTool( + tool.name, + { + description: tool.description, + inputSchema: schema, + annotations: tool.annotations, + }, + (args, ctx) => { + const req = store.getStore(); + if (!req) throw new Error("MCP request context missing"); + return tool.run(req, args, ctx.mcpReq.signal); + }, + ); + return server; + }; + factory(); + const handler = toNodeHandler( + createMcpHandler(factory, { legacy: "stateless" }), + ); + this.context.addRoute( + "all", + "/mcp", + originGuard(this.config.allowedOrigins), + (req, res, next) => { + Promise.resolve( + store.run(req, () => handler(req, res, req.body)), + ).catch(next); + }, + ); + this.context.addMiddleware( + "/mcp", + mcpErrorHandler as unknown as RequestHandler, + ); + } +} + +export function mcp(config: McpPluginConfig) { + return toPlugin(McpPlugin)({ ...config, serverName: config.name }); +} diff --git a/packages/appkit/src/plugins/mcp/tests/mcp.test.ts b/packages/appkit/src/plugins/mcp/tests/mcp.test.ts new file mode 100644 index 000000000..966a94509 --- /dev/null +++ b/packages/appkit/src/plugins/mcp/tests/mcp.test.ts @@ -0,0 +1,285 @@ +import type { Server } from "node:http"; + +import express from "express"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; + +import { AppKitMcpClient } from "../../../connectors/mcp/client"; +import { getCallerContext } from "../../../context/execution-context"; +import { tool } from "../../../core/agent/tools/tool"; +import { AuthenticationError } from "../../../errors"; +import { createTestPluginContext } from "../../../testing/test-plugin-context"; +import { McpPlugin } from "../mcp"; + +const token = { + "x-forwarded-access-token": "token", + "x-forwarded-user": "alice", +}; +const headers = { + "content-type": "application/json", + accept: "application/json, text/event-stream", + "mcp-protocol-version": "2025-03-26", +}; + +describe("MCP HTTP", () => { + let server: Server; + let url: string; + let fake: ReturnType; + beforeEach(async () => { + fake = createTestPluginContext( + { + lakebase: { + query: () => getCallerContext()?.principal.userId ?? "app", + }, + }, + { + env: { NODE_ENV: "test", DATABRICKS_HOST: "https://workspace.example" }, + }, + ); + const definition = fake.providers.get("lakebase")?.tools[0]; + if (!definition) throw new Error("Missing Lakebase definition"); + definition.annotations = { effect: "read" }; + const app = express(); + app.use((req, _res, next) => + req.headers["x-test-401"] + ? next( + new AuthenticationError("secret", { + clientMessage: "Login required", + }), + ) + : next(), + ); + app.use((req, _res, next) => + req.headers["x-test-500"] + ? next(new Error("sensitive server failure")) + : next(), + ); + app.use(express.json({ limit: "1kb" })); + fake.ctx.registerAsRouteTarget({ addExtension: (fn) => fn(app) }); + const plugin = new McpPlugin({ + name: "mcp", + serverName: "test", + context: fake.ctx, + allowedOrigins: ["https://allowed.example"], + tools: (plugins: any) => ({ + ...plugins.lakebase.toolkit(), + user: tool({ + description: "user", + schema: z.object({}), + scopes: ["sql"], + execute: () => getCallerContext()?.principal.userId ?? "app", + }), + app: tool({ + description: "app", + schema: z.object({}), + runAs: "app", + annotations: { effect: "read" }, + execute: () => getCallerContext()?.principal.userId ?? "app", + }), + scope: tool({ + description: "scope", + schema: z.object({}), + runAs: "app", + execute: () => { + throw new Error("required scopes: sql [ReqId: private]"); + }, + }), + failure: tool({ + description: "failure", + schema: z.object({}), + runAs: "app", + execute: () => { + throw new Error("private detail"); + }, + }), + }), + }); + await plugin.setup(); + server = await new Promise((resolve) => { + const s = app.listen(0, "127.0.0.1", () => resolve(s)); + }); + url = `http://127.0.0.1:${(server.address() as { port: number }).port}/mcp`; + }); + afterEach(async () => { + await new Promise((resolve, reject) => + server.close((err) => (err ? reject(err) : resolve())), + ); + fake.restore?.(); + vi.restoreAllMocks(); + }); + async function rpc( + method: string, + params: object = {}, + extra: Record = {}, + ) { + const response = await fetch(url, { + method: "POST", + headers: { ...headers, ...extra }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), + }); + const text = await response.text(); + const payload = text.startsWith("event:") + ? ( + text.split("\n").find((line) => line.startsWith("data: ")) ?? "" + ).slice(6) + : text; + return { response, body: JSON.parse(payload) as any }; + } + async function call(name: string, extra: Record = {}) { + return (await rpc("tools/call", { name, arguments: {} }, extra)).body + .result; + } + it("runs user and app tools on one endpoint; Lakebase remains app with a caller", async () => { + expect((await call("user", token)).content[0].text).toBe("alice"); + expect((await call("app", token)).content[0].text).toBe("app"); + expect((await call("lakebase.query", token)).content[0].text).toBe("app"); + const missing = await call("user"); + expect(missing.isError).toBe(true); + expect(missing.content[0].text).toContain("sql"); + expect((await call("app")).content[0].text).toBe("app"); + }); + it("sanitizes errors and returns missing scope", async () => { + const log = vi.spyOn(console, "error"); + expect((await call("scope")).content[0].text).toContain("sql"); + const failure = await call("failure"); + expect(failure.isError).toBe(true); + expect(failure.content[0].text).toBe('Tool "failure" failed.'); + expect(log.mock.calls.flat().join(" ")).toContain("private detail"); + }); + it("lists names and annotations", async () => { + const { body } = await rpc("tools/list"); + expect(body.result.tools.map((t: any) => t.name)).toEqual([ + "lakebase.query", + "user", + "app", + "scope", + "failure", + ]); + expect( + body.result.tools.find((t: any) => t.name === "app").annotations + .readOnlyHint, + ).toBe(true); + }); + it("maps parser and authentication errors", async () => { + const bad = await fetch(url, { method: "POST", headers, body: "{" }); + expect(bad.status).toBe(400); + expect(((await bad.json()) as any).error.code).toBe(-32700); + const large = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ value: "x".repeat(2000) }), + }); + expect(large.status).toBe(413); + expect(((await large.json()) as any).error.code).toBe(-32600); + const auth = await fetch(url, { + method: "POST", + headers: { ...headers, "x-test-401": "1" }, + body: "{}", + }); + expect(auth.status).toBe(401); + expect(((await auth.json()) as any).error).toEqual({ + code: -32000, + message: "Login required", + }); + }); + it("applies Origin policy and GET/DELETE return 405", async () => { + expect( + ( + await rpc( + "tools/list", + {}, + { + origin: "https://public.example", + "x-forwarded-host": "public.example", + }, + ) + ).response.status, + ).toBe(200); + for (const origin of [ + undefined, + new URL(url).origin, + "https://allowed.example", + ]) + expect( + (await rpc("tools/list", {}, origin ? { origin } : {})).response.status, + ).toBe(200); + for (const origin of ["https://foreign.example", "null", "not a url", ""]) + expect((await rpc("tools/list", {}, { origin })).response.status).toBe( + 403, + ); + for (const method of ["GET", "DELETE"]) { + const res = await fetch(url, { method }); + expect(res.status).toBe(405); + expect(res.headers.get("allow")).toBe("POST"); + } + }); + it("works with AppKitMcpClient 2025-03-26", async () => { + const client = new AppKitMcpClient( + "https://workspace.example", + async () => ({}), + { + workspaceHostname: "workspace.example", + trustedHosts: new Set(), + allowLocalhost: true, + }, + ); + await client.connect({ name: "local", url }); + expect(client.getAllToolDefinitions().map((t) => t.name)).toContain( + "mcp.local.app", + ); + expect(await client.callTool("mcp.local.app", {})).toBe("app"); + await client.close(); + }); +}); + +describe("MCP through AppKit", () => { + it("preserves the configured server name and catches the server parser's 413", async () => { + const { createTestApp } = await import("../../../testing/create-test-app"); + const { mcp } = await import("../mcp"); + const app = await createTestApp({ + plugins: [ + mcp({ + name: "sales", + tools: () => ({ + hello: tool({ + description: "hello", + schema: z.object({}), + runAs: "app", + execute: () => "world", + }), + }), + }), + ], + }); + try { + const response = await app.post("/mcp", { + headers, + body: { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-03-26", + capabilities: {}, + clientInfo: { name: "test", version: "1" }, + }, + }, + }); + const raw = await response.text(); + const data = raw.startsWith("event:") + ? ( + raw.split("\n").find((line) => line.startsWith("data: ")) ?? "" + ).slice(6) + : raw; + expect(JSON.parse(data).result.serverInfo.name).toBe("sales"); + const large = await app.post("/mcp", { + headers, + body: { data: "x".repeat(1_100_000) }, + }); + expect(large.status).toBe(413); + expect(((await large.json()) as any).error.code).toBe(-32600); + } finally { + await app.close(); + } + }); +}); diff --git a/packages/appkit/src/plugins/mcp/tests/tools.test.ts b/packages/appkit/src/plugins/mcp/tests/tools.test.ts new file mode 100644 index 000000000..f46008c5f --- /dev/null +++ b/packages/appkit/src/plugins/mcp/tests/tools.test.ts @@ -0,0 +1,231 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; + +import { + getCallerContext, + runInCallerContext, +} from "../../../context/execution-context"; +import { tool } from "../../../core/agent/tools/tool"; +import { createMockRequest, fakeUserContext } from "../../../testing/fixtures"; +import { createMockWorkspaceClient } from "../../../testing/mock-workspace-client"; +import { createTestPluginContext } from "../../../testing/test-plugin-context"; +import { checkScopes, mapAnnotations, resolveTools } from "../tools"; + +afterEach(() => vi.restoreAllMocks()); + +describe("MCP tools", () => { + it("keeps toolkit keys, filters unknown and mutating effects unless only names them", () => { + const fake = createTestPluginContext({ + sample: { read: "", write: "", update: "", delete: "", unknown: "" }, + }); + const defs = fake.providers.get("sample")?.tools ?? []; + for (const [i, effect] of ( + ["read", "write", "update", "destructive"] as const + ).entries()) + defs[i].annotations = { effect }; + const tools = resolveTools(fake.ctx, (plugins) => ({ + ...plugins.sample.toolkit(), + ...plugins.sample.toolkit({ + only: ["write", "update", "delete", "unknown"], + prefix: "chosen.", + }), + local: tool({ + description: "local", + schema: z.object({}), + execute: () => "ok", + }), + })); + expect(tools.map((t) => t.name)).toEqual([ + "sample.read", + "chosen.write", + "chosen.update", + "chosen.delete", + "chosen.unknown", + "local", + ]); + }); + + it("maps effects, legacy hints and idempotency", () => { + expect(mapAnnotations({ effect: "read", idempotent: true })).toEqual({ + readOnlyHint: true, + idempotentHint: true, + }); + expect(mapAnnotations({ effect: "write" })).toEqual({ + readOnlyHint: false, + destructiveHint: false, + }); + expect(mapAnnotations({ effect: "update" })).toEqual({ + readOnlyHint: false, + destructiveHint: false, + }); + expect(mapAnnotations({ effect: "destructive" })).toEqual({ + readOnlyHint: false, + destructiveHint: true, + }); + expect( + mapAnnotations({ readOnly: false, destructive: true, idempotent: false }), + ).toEqual({ + readOnlyHint: false, + destructiveHint: true, + idempotentHint: false, + }); + expect(mapAnnotations()).toEqual({}); + }); + + it("records user scopes and logs their union and app identity", async () => { + const info = vi.spyOn(console, "log"); + const warn = vi.spyOn(console, "warn"); + const fake = createTestPluginContext({}); + const tools = resolveTools(fake.ctx, () => ({ + a: tool({ + description: "a", + schema: z.object({}), + scopes: ["sql", "genie"], + execute: () => "", + }), + b: tool({ + description: "b", + schema: z.object({}), + scopes: ["sql"], + runAs: "app", + execute: () => "", + }), + })); + await checkScopes(tools); + expect(tools.map((t) => t.scopes)).toEqual([["sql", "genie"], []]); + expect(info.mock.calls.flat().join(" ")).toContain( + "Required user_api_scopes: sql, genie", + ); + expect(warn.mock.calls.flat().join(" ")).toContain( + "runs as the App service principal", + ); + }); + + it("uses the provider toolkit and derives manifest and resource scopes", () => { + const fake = createTestPluginContext({ reports: { read: "ok" } }); + const provider = fake.ctx.getToolProviders()[0].provider; + Object.defineProperty(provider, "constructor", { + value: { + manifest: { + scopes: ["genie"], + resources: { + required: [{ type: "volume", fields: {} }], + optional: [{ type: "sql_warehouse", fields: {} }], + }, + }, + }, + }); + const def = fake.providers.get("reports")?.tools[0]; + if (!def) throw new Error("Missing definition"); + def.annotations = { effect: "read" }; + const ownToolkit = vi.fn(() => ({ + renamed: { + __toolkitRef: true as const, + pluginName: "reports", + localName: "read", + def, + }, + })); + Object.assign(provider, { toolkit: ownToolkit }); + const [entry] = resolveTools(fake.ctx, (plugins) => + plugins.reports.toolkit({ + only: ["read"], + rename: { read: "renamed" }, + runAs: "user", + }), + ); + expect(ownToolkit).toHaveBeenCalledWith({ + only: ["read"], + rename: { read: "renamed" }, + }); + expect(entry.name).toBe("renamed"); + expect(entry.scopes).toEqual(["genie", "files", "sql"]); + }); + + it("forces Lakebase to app and refuses explicit user", async () => { + const warn = vi.spyOn(console, "warn"); + const fake = createTestPluginContext({ + lakebase: { query: () => getCallerContext()?.principal.userId ?? "app" }, + }); + const definition = fake.providers.get("lakebase")?.tools[0]; + if (!definition) throw new Error("Missing Lakebase definition"); + definition.annotations = { effect: "read" }; + const [entry] = resolveTools(fake.ctx, (plugins) => + plugins.lakebase.toolkit(), + ); + expect(entry.runAs).toBe("app"); + expect(entry.scopes).toEqual([]); + const caller = fakeUserContext(createMockWorkspaceClient(), { + workspaceId: Promise.resolve("test"), + })("token", "alice"); + const inside = await runInCallerContext(caller, () => + entry.run( + createMockRequest({ obo: true }), + {}, + new AbortController().signal, + ), + ); + expect(inside.content[0].text).toBe("app"); + expect( + resolveTools(fake.ctx, (plugins) => + plugins.lakebase.toolkit({ runAs: "app" }), + )[0].runAs, + ).toBe("app"); + expect(warn.mock.calls.flat().join(" ")).toContain( + "no workspace test yet confirms", + ); + expect( + ( + await entry.run( + createMockRequest({ obo: true }), + {}, + new AbortController().signal, + ) + ).content[0].text, + ).toBe("app"); + expect(() => + resolveTools(fake.ctx, (plugins) => + plugins.lakebase.toolkit({ runAs: "user" }), + ), + ).toThrow("no workspace test yet confirms"); + }); + + it("rejects hosted tools", () => { + const fake = createTestPluginContext({}); + expect(() => + resolveTools(fake.ctx, () => ({ hosted: { type: "hosted" } as never })), + ).toThrow("not a function tool or toolkit entry"); + }); + + it("warns for missing scopes and failed App lookup", async () => { + const warn = vi.spyOn(console, "warn"); + const fake = createTestPluginContext( + {}, + { + env: { DATABRICKS_APP_NAME: "test" }, + responses: { "apps.getApp": { effectiveUserApiScopes: ["genie"] } }, + }, + ); + const tools = resolveTools(fake.ctx, () => ({ + a: tool({ + description: "a", + schema: z.object({}), + scopes: ["sql", "genie"], + execute: () => "", + }), + })); + await checkScopes(tools); + expect(warn.mock.calls.flat().join(" ")).toContain( + "missing user_api_scopes: sql", + ); + fake.restore?.(); + createTestPluginContext( + {}, + { env: { DATABRICKS_APP_NAME: "test" }, strict: true }, + ); + await checkScopes(tools); + expect(warn.mock.calls.flat().join(" ")).toContain( + "Could not check App user_api_scopes", + ); + }); +}); diff --git a/packages/appkit/src/plugins/mcp/tools.ts b/packages/appkit/src/plugins/mcp/tools.ts new file mode 100644 index 000000000..f15b240da --- /dev/null +++ b/packages/appkit/src/plugins/mcp/tools.ts @@ -0,0 +1,241 @@ +import type { Request } from "express"; +import { SCOPE_BY_TYPE, type ToolAnnotations, type ToolProvider } from "shared"; + +import { + getWorkspaceClient, + runOutsideCallerScope, +} from "../../context/execution-context"; +import { createRequestScope } from "../../context/request-scope"; +import { getPluginResourceTypes } from "../../context/resource-capabilities"; +import { createPluginsProxy } from "../../core/agent/plugins-map"; +import { getRequiredScopes } from "../../core/agent/scope-error"; +import { resolveToolkitFromProvider } from "../../core/agent/toolkit-resolver"; +import { isFunctionTool } from "../../core/agent/tools/function-tool"; +import { + isToolkitEntry, + type AgentTools, + type PluginToolkitProvider, + type Plugins, + type ToolkitEntry, +} from "../../core/agent/types"; +import type { PluginContext } from "../../core/plugin-context"; +import { AuthenticationError } from "../../errors"; +import { createLogger } from "../../logging/logger"; + +const logger = createLogger("mcp"); +const lakebaseReason = + "Lakebase tools run as the App: no workspace test yet confirms that an Apps-forwarded user token can mint a Lakebase credential (AppKit doesn't map the postgres scope)."; +type Identity = "user" | "app"; + +interface ServedTool { + name: string; + description: string; + parameters: Record; + annotations: ReturnType; + runAs: Identity; + scopes: string[]; + run( + req: Request, + args: Record, + signal: AbortSignal, + ): Promise<{ content: { type: "text"; text: string }[]; isError?: boolean }>; +} + +export function mapAnnotations(annotations?: ToolAnnotations) { + const mapped: { + readOnlyHint?: boolean; + destructiveHint?: boolean; + idempotentHint?: boolean; + } = {}; + if (annotations?.effect) { + mapped.readOnlyHint = annotations.effect === "read"; + if (annotations.effect !== "read") + mapped.destructiveHint = annotations.effect === "destructive"; + } else { + if (annotations?.readOnly !== undefined) + mapped.readOnlyHint = annotations.readOnly; + if (annotations?.destructive !== undefined) + mapped.destructiveHint = annotations.destructive; + } + if (annotations?.idempotent !== undefined) + mapped.idempotentHint = annotations.idempotent; + return mapped; +} + +function pluginScopes(provider: ToolProvider): string[] { + const manifest = ( + provider.constructor as { + manifest?: { + scopes?: string[]; + resources?: { + required?: { type: string }[]; + optional?: { type: string }[]; + }; + }; + } + ).manifest; + const types = [ + ...getPluginResourceTypes(provider), + ...(manifest?.resources?.required ?? []).map((r) => r.type), + ...(manifest?.resources?.optional ?? []).map((r) => r.type), + ]; + const resourceScopes = types.flatMap((type) => + Object.hasOwn(SCOPE_BY_TYPE, type) + ? [SCOPE_BY_TYPE[type as keyof typeof SCOPE_BY_TYPE]] + : [], + ); + return [...new Set([...(manifest?.scopes ?? []), ...resourceScopes])]; +} + +function toolkitIdentity(name: string, requested?: Identity): Identity { + // Stopgap: remove after a workspace test confirms Apps-forwarded user tokens can mint Lakebase credentials. + if (name === "lakebase") { + if (requested === "user") throw new Error(lakebaseReason); + return "app"; + } + return requested ?? "user"; +} + +export function resolveTools( + context: PluginContext, + build: (plugins: Plugins) => AgentTools, +): ServedTool[] { + const providers = new Map( + context.getToolProviders().map(({ name, provider }) => [name, provider]), + ); + const identities = new WeakMap(); + const map: Record = {}; + for (const [name, provider] of providers) { + map[name] = { + toolkit: (options = {}) => { + const { runAs, ...rest } = options; + const identity = toolkitIdentity(name, runAs); + const entries = resolveToolkitFromProvider(name, provider, rest); + for (const [key, entry] of Object.entries(entries)) { + if ( + rest.only === undefined && + (entry.annotations ?? entry.def.annotations)?.effect !== "read" + ) + delete entries[key]; + else identities.set(entry, identity); + } + return entries; + }, + }; + } + const nonProviders = new Set( + context.getPluginNames().filter((name) => !(name in map)), + ); + const selected = build( + createPluginsProxy(map, "MCP: tools(plugins)", nonProviders), + ); + const tools: ServedTool[] = []; + for (const [name, entry] of Object.entries(selected)) { + const toolkit = isToolkitEntry(entry); + if (!toolkit && !isFunctionTool(entry)) + throw new Error( + `MCP tool "${name}" is not a function tool or toolkit entry`, + ); + const provider = toolkit ? providers.get(entry.pluginName) : undefined; + if (toolkit && !provider) + throw new Error(`MCP tool "${name}" has no registered provider`); + const runAs = toolkit + ? (identities.get(entry) ?? toolkitIdentity(entry.pluginName)) + : (entry.runAs ?? "user"); + const scopes = + runAs === "app" + ? [] + : toolkit + ? pluginScopes(provider as ToolProvider) + : [...new Set(entry.scopes ?? [])]; + const definition = toolkit ? entry.def : entry; + const annotations = toolkit + ? (entry.annotations ?? entry.def.annotations) + : entry.annotations; + logger.info( + 'Tool "%s": runAs=%s scopes=%s', + name, + runAs, + scopes.join(", ") || "(none)", + ); + if (runAs === "app") + logger.warn( + 'Tool "%s" runs as the App service principal.%s', + name, + toolkit && entry.pluginName === "lakebase" ? ` ${lakebaseReason}` : "", + ); + tools.push({ + name, + description: definition.description ?? name, + parameters: (definition.parameters ?? { + type: "object", + properties: {}, + }) as Record, + annotations: mapAnnotations(annotations), + runAs, + scopes, + async run(req, args, signal) { + try { + let result: unknown; + if (toolkit) { + result = + runAs === "user" + ? await context.executeTool( + req, + entry.pluginName, + entry.localName, + args, + signal, + ) + : await runOutsideCallerScope(() => + (provider as ToolProvider).executeAgentTool( + entry.localName, + args, + AbortSignal.any([signal, AbortSignal.timeout(300_000)]), + ), + ); + } else { + result = await (runAs === "user" + ? createRequestScope(req).run(() => entry.execute(args)) + : runOutsideCallerScope(() => entry.execute(args))); + } + const text = + typeof result === "string" + ? result + : (JSON.stringify(result) ?? ""); + return { content: [{ type: "text", text }] }; + } catch (error) { + logger.error('Tool "%s" failed: %O', name, error); + const missing = getRequiredScopes(error); + const text = + error instanceof AuthenticationError + ? `Tool "${name}" requires a user token. Declare user_api_scopes: ${scopes.join(", ") || "(none specified)"}.` + : missing !== undefined + ? `Tool "${name}" requires user_api_scopes: ${missing}.` + : `Tool "${name}" failed.`; + return { isError: true, content: [{ type: "text", text }] }; + } + }, + }); + } + return tools; +} + +export async function checkScopes(tools: ServedTool[]): Promise { + const scopes = [...new Set(tools.flatMap((tool) => tool.scopes))]; + logger.info("Required user_api_scopes: %s", scopes.join(", ") || "(none)"); + const name = process.env.DATABRICKS_APP_NAME; + if (!name) return; + try { + const app = await runOutsideCallerScope(() => + getWorkspaceClient().apps.getApp({ name }), + ); + const missing = scopes.filter( + (scope) => !app.effectiveUserApiScopes?.includes(scope), + ); + if (missing.length) + logger.warn("App is missing user_api_scopes: %s", missing.join(", ")); + } catch (error) { + logger.warn("Could not check App user_api_scopes: %O", error); + } +} diff --git a/packages/appkit/src/plugins/mcp/types.ts b/packages/appkit/src/plugins/mcp/types.ts new file mode 100644 index 000000000..77799110a --- /dev/null +++ b/packages/appkit/src/plugins/mcp/types.ts @@ -0,0 +1,10 @@ +import type { BasePluginConfig } from "shared"; + +import type { AgentTools, Plugins } from "../../core/agent/types"; + +export interface McpPluginConfig extends BasePluginConfig { + name: string; + description?: string; + tools: (plugins: Plugins) => AgentTools; + allowedOrigins?: string[]; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ef924c30e..7e95489cb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -338,6 +338,12 @@ importers: '@databricks/sdk-warehouses': specifier: 0.53.0 version: 0.53.0 + '@modelcontextprotocol/node': + specifier: 2.1.2 + version: 2.1.2(@modelcontextprotocol/server@2.4.0) + '@modelcontextprotocol/server': + specifier: 2.4.0 + version: 2.4.0 '@opentelemetry/api': specifier: 1.9.0 version: 1.9.0 @@ -2585,6 +2591,12 @@ packages: '@hapi/topo@5.1.0': resolution: {integrity: sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==} + '@hono/node-server@2.1.11': + resolution: {integrity: sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog==} + engines: {node: '>=20'} + peerDependencies: + hono: ^4 || ^5.0.0-0 + '@humanfs/core@0.19.1': resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} engines: {node: '>=18.18.0'} @@ -2873,6 +2885,20 @@ packages: engines: {node: '>=18'} hasBin: true + '@modelcontextprotocol/core@2.4.0': + resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==} + engines: {node: '>=20'} + + '@modelcontextprotocol/node@2.1.2': + resolution: {integrity: sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==} + engines: {node: '>=20'} + peerDependencies: + '@modelcontextprotocol/server': ^2.4.0 + + '@modelcontextprotocol/server@2.4.0': + resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==} + engines: {node: '>=20'} + '@napi-rs/wasm-runtime@1.1.1': resolution: {integrity: sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==} @@ -8277,6 +8303,10 @@ packages: hoist-non-react-statics@3.3.2: resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==} + hono@4.13.23: + resolution: {integrity: sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg==} + engines: {node: '>=16.9.0'} + hookable@6.0.1: resolution: {integrity: sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw==} @@ -15466,6 +15496,10 @@ snapshots: dependencies: '@hapi/hoek': 9.3.0 + '@hono/node-server@2.1.11(hono@4.13.23)': + dependencies: + hono: 4.13.23 + '@humanfs/core@0.19.1': {} '@humanfs/node@0.16.7': @@ -15822,6 +15856,21 @@ snapshots: - supports-color - utf-8-validate + '@modelcontextprotocol/core@2.4.0': + dependencies: + zod: 4.6.7 + + '@modelcontextprotocol/node@2.1.2(@modelcontextprotocol/server@2.4.0)': + dependencies: + '@hono/node-server': 2.1.11(hono@4.13.23) + '@modelcontextprotocol/server': 2.4.0 + hono: 4.13.23 + + '@modelcontextprotocol/server@2.4.0': + dependencies: + '@modelcontextprotocol/core': 2.4.0 + zod: 4.6.7 + '@napi-rs/wasm-runtime@1.1.1': dependencies: '@emnapi/core': 1.8.1 @@ -21699,6 +21748,8 @@ snapshots: dependencies: react-is: 16.13.1 + hono@4.13.23: {} + hookable@6.0.1: {} hosted-git-info@8.1.0: diff --git a/template/appkit.plugins.json b/template/appkit.plugins.json index e32eb3ccb..a511e14a8 100644 --- a/template/appkit.plugins.json +++ b/template/appkit.plugins.json @@ -475,6 +475,17 @@ } } }, + "mcp": { + "name": "mcp", + "displayName": "MCP Server Plugin", + "description": "Serve AppKit tools over MCP", + "package": "@databricks/appkit", + "resources": { + "required": [], + "optional": [] + }, + "stability": "beta" + }, "server": { "name": "server", "displayName": "Server Plugin", From 41bbc8ae5b9c392ba651c152ab819aee75c98d6b Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:06:46 +0000 Subject: [PATCH 2/5] test(appkit): include MCP in plugin registry fixture Signed-off-by: mario.cadenas Co-authored-by: Isaac --- .../appkit/src/plugins/database/tests/operations.types.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/appkit/src/plugins/database/tests/operations.types.test.ts b/packages/appkit/src/plugins/database/tests/operations.types.test.ts index fb5516429..035e179a2 100644 --- a/packages/appkit/src/plugins/database/tests/operations.types.test.ts +++ b/packages/appkit/src/plugins/database/tests/operations.types.test.ts @@ -99,7 +99,7 @@ export const getPost = defineOperation({ type _Plugins = Expect< Equal< Exclude, - "agents" | "aiSearch" | "analytics" | "design" | "files" | "genie" | "jobs" | "lakebase" | "server" | "serving" + "agents" | "aiSearch" | "analytics" | "design" | "files" | "genie" | "jobs" | "lakebase" | "mcp" | "server" | "serving" > >; type _Optional = Expect>; From 509974b69f97aa5d7c05323decce367de8736bc0 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:19:24 +0000 Subject: [PATCH 3/5] test(appkit): assert MCP identity and scope logs Signed-off-by: mario.cadenas Co-authored-by: Isaac --- packages/appkit/src/plugins/mcp/tests/tools.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/appkit/src/plugins/mcp/tests/tools.test.ts b/packages/appkit/src/plugins/mcp/tests/tools.test.ts index f46008c5f..878d75b94 100644 --- a/packages/appkit/src/plugins/mcp/tests/tools.test.ts +++ b/packages/appkit/src/plugins/mcp/tests/tools.test.ts @@ -93,6 +93,12 @@ describe("MCP tools", () => { })); await checkScopes(tools); expect(tools.map((t) => t.scopes)).toEqual([["sql", "genie"], []]); + expect(info.mock.calls.flat().join(" ")).toContain( + 'Tool "a": runAs=user scopes=sql, genie', + ); + expect(info.mock.calls.flat().join(" ")).toContain( + 'Tool "b": runAs=app scopes=(none)', + ); expect(info.mock.calls.flat().join(" ")).toContain( "Required user_api_scopes: sql, genie", ); From fb2ba7a79ebc93124a840a3ef64bf732b17a2627 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:44:03 +0000 Subject: [PATCH 4/5] chore(appkit): keep the existing dependency order Adding the MCP SDK re-sorted unrelated entries in package.json. Restore the original order and keep only the two new exact pins. Co-authored-by: Isaac Signed-off-by: mario.cadenas --- packages/appkit/package.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/appkit/package.json b/packages/appkit/package.json index 8a9aa3a80..6ad45fc84 100644 --- a/packages/appkit/package.json +++ b/packages/appkit/package.json @@ -75,20 +75,20 @@ "@databricks/sdk-auth": "0.51.0", "@databricks/sdk-core": "0.51.0", "@databricks/sdk-database": "0.51.0", - "@databricks/sdk-experiments": "0.52.0", "@databricks/sdk-files": "0.52.0", + "@databricks/sdk-experiments": "0.52.0", "@databricks/sdk-genie": "0.54.0", + "@databricks/sdk-uc-functions": "0.51.0", "@databricks/sdk-jobs": "0.57.0", "@databricks/sdk-modelserving": "0.53.0", - "@databricks/sdk-options": "0.51.0", - "@databricks/sdk-postgres": "0.52.0", - "@databricks/sdk-scim": "0.51.0", - "@databricks/sdk-statementexecution": "0.52.0", "@databricks/sdk-uc-connections": "0.52.0", - "@databricks/sdk-uc-functions": "0.51.0", "@databricks/sdk-uc-tables": "0.52.0", "@databricks/sdk-uc-volumes": "0.51.0", "@databricks/sdk-vectorsearch": "0.51.0", + "@databricks/sdk-options": "0.51.0", + "@databricks/sdk-postgres": "0.52.0", + "@databricks/sdk-scim": "0.51.0", + "@databricks/sdk-statementexecution": "0.52.0", "@databricks/sdk-warehouses": "0.53.0", "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", From 9d24c80f4f94e36d3dd9c407fbeea1b3849c9aa3 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:44:07 +0000 Subject: [PATCH 5/5] docs(appkit): document the mcp() plugin config Co-authored-by: Isaac Signed-off-by: mario.cadenas --- docs/docs/api/appkit/Function.mcp.md | 3 +++ docs/docs/api/appkit/Interface.McpPluginConfig.md | 10 +++++++++- docs/docs/api/appkit/index.md | 4 ++-- packages/appkit/src/plugins/mcp/mcp.ts | 5 +++++ packages/appkit/src/plugins/mcp/types.ts | 5 +++++ 5 files changed, 24 insertions(+), 3 deletions(-) diff --git a/docs/docs/api/appkit/Function.mcp.md b/docs/docs/api/appkit/Function.mcp.md index 50b648ed9..a3a723880 100644 --- a/docs/docs/api/appkit/Function.mcp.md +++ b/docs/docs/api/appkit/Function.mcp.md @@ -4,6 +4,9 @@ function mcp(config: McpPluginConfig): PluginData; ``` +Serve the tools returned by `config.tools(plugins)` as one MCP server at `POST /mcp` +(stateless streamable HTTP), for registration as a Unity Catalog MCP Service. + ## Parameters | Parameter | Type | diff --git a/docs/docs/api/appkit/Interface.McpPluginConfig.md b/docs/docs/api/appkit/Interface.McpPluginConfig.md index dbe8b820f..a96902c14 100644 --- a/docs/docs/api/appkit/Interface.McpPluginConfig.md +++ b/docs/docs/api/appkit/Interface.McpPluginConfig.md @@ -1,6 +1,6 @@ # Interface: McpPluginConfig -Base configuration interface for AppKit plugins +Configuration for the beta [mcp](Function.mcp.md) plugin. ## Extends @@ -20,6 +20,8 @@ Base configuration interface for AppKit plugins optional allowedOrigins: string[]; ``` +Cross-origin browser origins to accept, e.g. `https://portal.example.com`. + *** ### description? @@ -28,6 +30,8 @@ optional allowedOrigins: string[]; optional description: string; ``` +MCP server description reported to clients in `serverInfo`. + *** ### host? @@ -48,6 +52,8 @@ optional host: string; name: string; ``` +MCP server name reported to clients in `serverInfo`. + #### Overrides [`BasePluginConfig`](Interface.BasePluginConfig.md).[`name`](Interface.BasePluginConfig.md#name) @@ -89,6 +95,8 @@ optional telemetry: TelemetryOptions; tools: (plugins: Plugins) => AgentTools; ``` +Returns exactly the tools `/mcp` serves: toolkit entries and `tool()` definitions. + #### Parameters | Parameter | Type | diff --git a/docs/docs/api/appkit/index.md b/docs/docs/api/appkit/index.md index d8318b696..b592f2cd2 100644 --- a/docs/docs/api/appkit/index.md +++ b/docs/docs/api/appkit/index.md @@ -94,7 +94,7 @@ surface with `@databricks/appkit/beta`. Not meant for application imports. | [LakebasePoolManager](Interface.LakebasePoolManager.md) | Manages multiple Lakebase connection pools keyed by an identifier (e.g. userId). | | [MatchResult](Interface.MatchResult.md) | Result of a deterministic matcher run against a value. | | [McpConnectAllResult](Interface.McpConnectAllResult.md) | Per-endpoint outcome of [AppKitMcpClient.connectAll](Class.AppKitMcpClient.md#connectall). Callers (the agents plugin in particular) use the split to warn at startup when some MCP servers are unreachable without aborting boot for the rest. | -| [McpPluginConfig](Interface.McpPluginConfig.md) | Base configuration interface for AppKit plugins | +| [McpPluginConfig](Interface.McpPluginConfig.md) | Configuration for the beta [mcp](Function.mcp.md) plugin. | | [Message](Interface.Message.md) | - | | [OperationContext](Interface.OperationContext.md) | What `allow` and `execute` receive: the policy context and the loaded resource. | | [OperationDefinition](Interface.OperationDefinition.md) | One immutable operation descriptor. Nothing in it runs until a request does. | @@ -276,7 +276,7 @@ surface with `@databricks/appkit/beta`. Not meant for application imports. | [loadAgentsFromDir](Function.loadAgentsFromDir.md) | Scans a directory for one subdirectory per agent, each containing `agent.md` (frontmatter + body). Produces an `AgentDefinition` record keyed by agent id (folder name). Throws on frontmatter errors or unresolved references. Returns an empty map if the directory does not exist. | | [loadRootEvalConfig](Function.loadRootEvalConfig.md) | Load the root `evals.config.ts` under `rootDir` (the project root), or return `undefined` when there is none. This is the run-wide config carrying `baseUrl`/`webServer`; the CLI reads it to resolve options and manage the app-under-test lifecycle before calling [runEvalsInDir](Function.runEvalsInDir.md). | | [matches](Function.matches.md) | Passes when the value matches `pattern`. | -| [mcp](Function.mcp.md) | - | +| [mcp](Function.mcp.md) | Serve the tools returned by `config.tools(plugins)` as one MCP server at `POST /mcp` (stateless streamable HTTP), for registration as a Unity Catalog MCP Service. | | [mcpServer](Function.mcpServer.md) | Factory for declaring a custom MCP server tool. | | [normalizeHost](Function.normalizeHost.md) | Ensure the host has a scheme (Databricks env often lacks `https://`). | | [parseTextToolCalls](Function.parseTextToolCalls.md) | Parses text-based tool calls from model output. | diff --git a/packages/appkit/src/plugins/mcp/mcp.ts b/packages/appkit/src/plugins/mcp/mcp.ts index fc4d28b3e..670856d66 100644 --- a/packages/appkit/src/plugins/mcp/mcp.ts +++ b/packages/appkit/src/plugins/mcp/mcp.ts @@ -59,6 +59,7 @@ export class McpPlugin extends Plugin { ); return server; }; + // Build once at startup so an invalid or duplicate tool name fails setup, not the first request. factory(); const handler = toNodeHandler( createMcpHandler(factory, { legacy: "stateless" }), @@ -80,6 +81,10 @@ export class McpPlugin extends Plugin { } } +/** + * Serve the tools returned by `config.tools(plugins)` as one MCP server at `POST /mcp` + * (stateless streamable HTTP), for registration as a Unity Catalog MCP Service. + */ export function mcp(config: McpPluginConfig) { return toPlugin(McpPlugin)({ ...config, serverName: config.name }); } diff --git a/packages/appkit/src/plugins/mcp/types.ts b/packages/appkit/src/plugins/mcp/types.ts index 77799110a..0fad78011 100644 --- a/packages/appkit/src/plugins/mcp/types.ts +++ b/packages/appkit/src/plugins/mcp/types.ts @@ -2,9 +2,14 @@ import type { BasePluginConfig } from "shared"; import type { AgentTools, Plugins } from "../../core/agent/types"; +/** Configuration for the beta {@link mcp} plugin. */ export interface McpPluginConfig extends BasePluginConfig { + /** MCP server name reported to clients in `serverInfo`. */ name: string; + /** MCP server description reported to clients in `serverInfo`. */ description?: string; + /** Returns exactly the tools `/mcp` serves: toolkit entries and `tool()` definitions. */ tools: (plugins: Plugins) => AgentTools; + /** Cross-origin browser origins to accept, e.g. `https://portal.example.com`. */ allowedOrigins?: string[]; }