From fa3ee39faa2a2cdf7196d59f4b7298eb2836522f Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Wed, 2 Dec 2026 22:23:28 +0000 Subject: [PATCH 1/3] feat(appkit): add `appkit mcp register` / `unregister` commands Register an AppKit app as a Unity Catalog MCP Service (config.source_app -> the app's /mcp) through `databricks api`, so Unity Gateway serves it at /ai-gateway/mcp-services/. Creates or updates the service, grants EXECUTE on it and CAN_USE on the app per --grant, prints the gateway URL, and explains when the workspace lacks App sources. `unregister` deletes the service and leaves the app running. Stopgap until Asset Bundles can declare an App-backed MCP Service; it lives in commands/mcp/ so it can be deleted in one go. Signed-off-by: mario.cadenas Co-authored-by: Isaac --- docs/docs/development/mcp-register.md | 37 +++ .../src/cli/commands/mcp/databricks-cli.ts | 67 ++++++ packages/shared/src/cli/commands/mcp/index.ts | 13 ++ .../src/cli/commands/mcp/register.test.ts | 218 ++++++++++++++++++ .../shared/src/cli/commands/mcp/register.ts | 145 ++++++++++++ .../shared/src/cli/commands/mcp/unregister.ts | 18 ++ packages/shared/src/cli/index.ts | 2 + 7 files changed, 500 insertions(+) create mode 100644 docs/docs/development/mcp-register.md create mode 100644 packages/shared/src/cli/commands/mcp/databricks-cli.ts create mode 100644 packages/shared/src/cli/commands/mcp/index.ts create mode 100644 packages/shared/src/cli/commands/mcp/register.test.ts create mode 100644 packages/shared/src/cli/commands/mcp/register.ts create mode 100644 packages/shared/src/cli/commands/mcp/unregister.ts diff --git a/docs/docs/development/mcp-register.md b/docs/docs/development/mcp-register.md new file mode 100644 index 000000000..8684d7bd6 --- /dev/null +++ b/docs/docs/development/mcp-register.md @@ -0,0 +1,37 @@ +--- +sidebar_position: 7 +--- + +# Register an app as an MCP Service + +:::caution Stopgap +`appkit mcp register` exists only until Asset Bundles can declare an App-backed MCP Service. When that lands, declare the service in `databricks.yml` and this command will be removed. +::: + +`appkit mcp register` registers an AppKit app (its `/mcp` endpoint) as a Unity Catalog MCP Service, so Unity Gateway serves it at `/ai-gateway/mcp-services/`. It shells out to the Databricks CLI (`databricks api`) and uses its authentication, so it needs no credentials of its own. + +```bash +npx @databricks/appkit mcp register main.default.my_app --app my-app \ + --grant data-team --grant someone@example.com --profile my-profile +``` + +- ``: the MCP Service to create, or update if it already exists. +- `--app `: the app to register. Defaults to the single app declared in `databricks.yml`. +- `--grant ` (repeatable): grants `EXECUTE` on the MCP Service and `CAN_USE` on the app. A principal containing `@` is a user, a UUID is a service principal (application ID), anything else is a group. Existing app permissions are kept. +- `--profile `: Databricks CLI profile, passed to every `databricks` call. + +The command prints the Unity Gateway URL to give MCP clients. `include_tool_selectors` is left unset; re-registering replaces the service's whole `config`, so any selectors set elsewhere are cleared. + +## Requirements + +- `CAN_MANAGE` on the app and `CREATE_SERVICE` on the schema. +- A workspace where the flag `databricks.unitycatalog.aigov.enableMcpAppSource` is on. Otherwise the command fails saying the workspace does not support App sources. +- Callers need `EXECUTE` on the MCP Service and, today, `CAN_USE` on the app (both given by `--grant`), plus `USE CATALOG` and `USE SCHEMA` on the parent catalog and schema, which `--grant` does not give. + +## Unregister + +```bash +npx @databricks/appkit mcp unregister main.default.my_app +``` + +Deletes the MCP Service. The app keeps running. diff --git a/packages/shared/src/cli/commands/mcp/databricks-cli.ts b/packages/shared/src/cli/commands/mcp/databricks-cli.ts new file mode 100644 index 000000000..805481c4d --- /dev/null +++ b/packages/shared/src/cli/commands/mcp/databricks-cli.ts @@ -0,0 +1,67 @@ +import { execFile } from "node:child_process"; + +/** Thrown when a `databricks api` call exits non-zero; `message` is the CLI's own output. */ +export class DatabricksApiError extends Error {} + +/** Runs `databricks api [--json body]` and returns parsed JSON (or undefined for an empty body). */ +export function databricksApi( + method: "get" | "post" | "patch" | "delete", + path: string, + opts: { body?: unknown; profile?: string } = {}, +): Promise { + const args = ["api", method, path]; + if (opts.body !== undefined) args.push("--json", JSON.stringify(opts.body)); + if (opts.profile) args.push("--profile", opts.profile); + return new Promise((resolve, reject) => { + execFile("databricks", args, (err, stdout, stderr) => { + if (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") { + return reject( + new Error( + "The `databricks` CLI was not found on PATH. Install it: https://docs.databricks.com/dev-tools/cli/install", + ), + ); + } + return reject( + new DatabricksApiError((stderr || stdout || err.message).trim()), + ); + } + try { + resolve(stdout.trim() ? JSON.parse(stdout) : undefined); + } catch { + resolve(undefined); + } + }); + }); +} + +/** Workspace host of the CLI's resolved auth, without trailing slash. */ +export async function workspaceHost(profile?: string): Promise { + const args = ["auth", "describe", "-o", "json"]; + if (profile) args.push("--profile", profile); + const out = await new Promise((resolve, reject) => { + execFile("databricks", args, (err, stdout, stderr) => + err ? reject(new Error((stderr || err.message).trim())) : resolve(stdout), + ); + }); + const host = JSON.parse(out)?.details?.host; + if (typeof host !== "string" || !host) { + throw new Error( + "Could not determine the workspace host from `databricks auth describe`.", + ); + } + return host.replace(/\/+$/, ""); +} + +/** Shared by register/unregister: the three-part name the UC API addresses a service by. */ +export function parseFqn(fqn: string): string { + const parts = fqn.split("."); + if (parts.length !== 3 || parts.some((p) => !p)) { + throw new Error( + `Invalid MCP service name "${fqn}": expected ...`, + ); + } + return fqn; +} + +export const SERVICES_PATH = "/api/2.1/unity-catalog/mcp-services"; diff --git a/packages/shared/src/cli/commands/mcp/index.ts b/packages/shared/src/cli/commands/mcp/index.ts new file mode 100644 index 000000000..23950cf11 --- /dev/null +++ b/packages/shared/src/cli/commands/mcp/index.ts @@ -0,0 +1,13 @@ +import { Command } from "commander"; + +import { mcpRegisterCommand } from "./register"; +import { mcpUnregisterCommand } from "./unregister"; + +/** + * Stopgap until Asset Bundles can declare an App-backed MCP Service: delete + * this folder and its one line in ../../index.ts then. + */ +export const mcpCommand = new Command("mcp") + .description("Register AppKit apps as Unity Catalog MCP Services") + .addCommand(mcpRegisterCommand) + .addCommand(mcpUnregisterCommand); diff --git a/packages/shared/src/cli/commands/mcp/register.test.ts b/packages/shared/src/cli/commands/mcp/register.test.ts new file mode 100644 index 000000000..fcbefc849 --- /dev/null +++ b/packages/shared/src/cli/commands/mcp/register.test.ts @@ -0,0 +1,218 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// Fake `databricks` CLI: each call is recorded; `respond` decides the outcome. +const calls: string[][] = []; +let respond: (args: string[]) => { out?: string; err?: string; code?: string }; +vi.mock("node:child_process", () => ({ + execFile: (_bin: string, args: string[], cb: any) => { + calls.push(args); + const r = respond(args); + if (r.err !== undefined || r.code) { + cb( + Object.assign(new Error(r.err ?? ""), { code: r.code }), + "", + r.err ?? "", + ); + } else cb(null, r.out ?? "", ""); + }, +})); + +import { mcpCommand } from "./index"; + +const FQN = "main.default.my_app"; +const ok = (out = "{}") => ({ out }); +const notFound = { err: "Error: 404 NOT_FOUND mcp service does not exist" }; +const api = (method: string) => calls.filter((c) => c[1] === method); +const body = (c: string[]) => JSON.parse(c[c.indexOf("--json") + 1]); + +async function run(...argv: string[]) { + // Commander keeps option values on the singleton between parses. + for (const c of mcpCommand.commands) { + c.setOptionValue("app", undefined); + c.setOptionValue("profile", undefined); + c.setOptionValue("grant", []); + } + await mcpCommand.parseAsync(argv, { from: "user" }); +} + +describe("appkit mcp", () => { + let log: ReturnType; + let errLog: ReturnType; + beforeEach(() => { + calls.length = 0; + process.exitCode = undefined; + log = vi.spyOn(console, "log").mockImplementation(() => {}); + errLog = vi.spyOn(console, "error").mockImplementation(() => {}); + respond = (args) => { + if (args[0] === "auth") + return ok('{"details":{"host":"https://ws.example.com/"}}'); + if (args[1] === "get") return notFound; + return ok(); + }; + }); + afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; + }); + + it("creates the service with source_app and no include_tool_selectors, then prints the gateway URL", async () => { + await run("register", FQN, "--app", "my-app"); + const [post] = api("post"); + expect(post[2]).toBe( + "/api/2.1/unity-catalog/mcp-services?mcp_service_id=my_app&parent=schemas%2Fmain.default", + ); + expect(body(post)).toEqual({ + config: { source_app: { name: "my-app", mcp_path: "/mcp" } }, + }); + expect(log).toHaveBeenCalledWith( + `Unity Gateway URL: https://ws.example.com/ai-gateway/mcp-services/${FQN}`, + ); + }); + + it("updates with PATCH when the service exists", async () => { + respond = (args) => + args[0] === "auth" ? ok('{"details":{"host":"https://h"}}') : ok(); + await run("register", FQN, "--app", "my-app"); + expect(api("post")).toHaveLength(0); + const [patch] = api("patch"); + expect(patch[2]).toBe( + `/api/2.1/unity-catalog/mcp-services/${FQN}?update_mask=config`, + ); + expect(body(patch).config.source_app).toEqual({ + name: "my-app", + mcp_path: "/mcp", + }); + }); + + it("grants EXECUTE on the service and CAN_USE on the app per principal", async () => { + await run( + "register", + FQN, + "--app", + "my-app", + "--grant", + "a@x.com", + "--grant", + "analysts", + "--grant", + "11111111-2222-3333-4444-555555555555", + ); + const patches = api("patch"); + expect(patches).toHaveLength(6); + expect(patches[0][2]).toBe( + `/api/2.1/unity-catalog/permissions/mcp_service/${FQN}`, + ); + expect(body(patches[0])).toEqual({ + changes: [{ principal: "a@x.com", add: ["EXECUTE"] }], + }); + expect(patches[1][2]).toBe("/api/2.0/permissions/apps/my-app"); + expect(body(patches[1]).access_control_list[0]).toEqual({ + user_name: "a@x.com", + permission_level: "CAN_USE", + }); + expect(body(patches[3]).access_control_list[0]).toEqual({ + group_name: "analysts", + permission_level: "CAN_USE", + }); + expect(body(patches[5]).access_control_list[0]).toEqual({ + service_principal_name: "11111111-2222-3333-4444-555555555555", + permission_level: "CAN_USE", + }); + }); + + it("explains a workspace without App sources enabled", async () => { + respond = (args) => + args[1] === "get" + ? notFound + : args[1] === "post" + ? { err: "Error: unknown field: source_app" } + : ok(); + await run("register", FQN, "--app", "my-app"); + expect(errLog.mock.calls[0][0]).toContain( + "databricks.unitycatalog.aigov.enableMcpAppSource", + ); + expect(process.exitCode).toBe(1); + }); + + it("does not report an app-not-found error mentioning source_app as flag-off", async () => { + respond = (args) => + args[1] === "get" + ? notFound + : { err: "Error: app 'x' not found (config.source_app.name)" }; + await run("register", FQN, "--app", "my-app"); + expect(errLog.mock.calls[0][0]).toBe( + "Error: app 'x' not found (config.source_app.name)", + ); + expect(process.exitCode).toBe(1); + }); + + it("passes other errors through with a non-zero exit", async () => { + respond = (args) => + args[1] === "get" ? notFound : { err: "Error: PERMISSION_DENIED" }; + await run("register", FQN, "--app", "my-app"); + expect(errLog.mock.calls[0][0]).toBe("Error: PERMISSION_DENIED"); + expect(process.exitCode).toBe(1); + }); + + it("passes --profile to every databricks call", async () => { + await run( + "register", + FQN, + "--app", + "my-app", + "--grant", + "g", + "--profile", + "dev", + ); + expect(calls.length).toBeGreaterThan(3); + for (const c of calls) expect(c.slice(-2)).toEqual(["--profile", "dev"]); + }); + + it("reads the app name from databricks.yml", async () => { + const dir = fs.mkdtempSync( + path.join(process.env.TMPDIR ?? os.tmpdir(), "mcp-"), + ); + fs.writeFileSync( + path.join(dir, "databricks.yml"), + "resources:\n apps:\n a:\n name: bundle-app\n", + ); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + await run("register", FQN); + cwd.mockRestore(); + fs.rmSync(dir, { recursive: true }); + expect(body(api("post")[0]).config.source_app.name).toBe("bundle-app"); + }); + + it("fails when no app is given or found, on a bad name, and when the CLI is missing", async () => { + const cwd = vi.spyOn(process, "cwd").mockReturnValue(os.tmpdir()); + await run("register", FQN); + expect(errLog.mock.calls[0][0]).toContain("pass --app"); + cwd.mockRestore(); + + await run("register", "a.b", "--app", "x"); + expect(errLog.mock.calls[1][0]).toContain("Invalid MCP service name"); + + respond = () => ({ err: "", code: "ENOENT" }); + await run("register", FQN, "--app", "x"); + expect(errLog.mock.calls[2][0]).toContain("`databricks` CLI was not found"); + expect(process.exitCode).toBe(1); + }); + + it("unregister deletes only the service", async () => { + await run("unregister", FQN, "--profile", "dev"); + expect(calls).toEqual([ + [ + "api", + "delete", + `/api/2.1/unity-catalog/mcp-services/${FQN}`, + "--profile", + "dev", + ], + ]); + }); +}); diff --git a/packages/shared/src/cli/commands/mcp/register.ts b/packages/shared/src/cli/commands/mcp/register.ts new file mode 100644 index 000000000..ed408ff56 --- /dev/null +++ b/packages/shared/src/cli/commands/mcp/register.ts @@ -0,0 +1,145 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { Command } from "commander"; +import yaml from "js-yaml"; + +import { DATABRICKS_YML_FILE } from "../../deploy-config"; +import { + DatabricksApiError, + databricksApi, + parseFqn, + SERVICES_PATH, + workspaceHost, +} from "./databricks-cli"; + +interface RegisterOptions { + app?: string; + grant: string[]; + profile?: string; +} + +/** App name from `databricks.yml` (`resources.apps..name`); errors if absent or ambiguous. */ +function appFromBundle(cwd: string): string { + let doc: any; + try { + doc = yaml.load( + fs.readFileSync(path.resolve(cwd, DATABRICKS_YML_FILE), "utf-8"), + ); + } catch { + doc = undefined; + } + const apps = Object.entries(doc?.resources?.apps ?? {}); + if (apps.length === 1) return apps[0][1]?.name ?? apps[0][0]; + throw new Error( + apps.length === 0 + ? `No app found: pass --app or run from a directory with a ${DATABRICKS_YML_FILE} that declares one.` + : `${DATABRICKS_YML_FILE} declares ${apps.length} apps: pass --app .`, + ); +} + +/** `@` means user, a UUID means service principal application id, anything else is a group. */ +export function principalField(principal: string): string { + if (principal.includes("@")) return "user_name"; + if ( + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( + principal, + ) + ) { + return "service_principal_name"; + } + return "group_name"; +} + +const FLAG_OFF = + /enableMcpAppSource|unknown field.*source_app|source_app.*(not (enabled|supported)|unknown field)|(feature|app source).*not (enabled|supported)/i; +const NOT_FOUND = /404|NOT_FOUND|does not exist|not found/i; + +export const mcpRegisterCommand = new Command("register") + .description("Register an AppKit app as a Unity Catalog MCP Service") + .argument("", "MCP Service name: ..") + .option("--app ", "App name (default: the app in databricks.yml)") + .option( + "--grant ", + "Principal to grant EXECUTE on the service and CAN_USE on the app (repeatable)", + (v: string, prev: string[]) => [...prev, v], + [] as string[], + ) + .option("--profile ", "Databricks CLI profile") + .action(async (fqn: string, opts: RegisterOptions) => { + try { + parseFqn(fqn); + const app = opts.app ?? appFromBundle(process.cwd()); + const { profile } = opts; + const [catalog, schema, name] = fqn.split("."); + const config = { source_app: { name: app, mcp_path: "/mcp" } }; + const url = `${SERVICES_PATH}/${fqn}`; + + const exists = await databricksApi("get", url, { profile }).then( + () => true, + (err) => { + if (err instanceof DatabricksApiError && NOT_FOUND.test(err.message)) + return false; + throw err; + }, + ); + try { + if (exists) { + // "config" replaces the whole config (source_app has no granular mask path). + await databricksApi("patch", `${url}?update_mask=config`, { + body: { config }, + profile, + }); + } else { + // parent and mcp_service_id are query params; the body is the service itself. + await databricksApi( + "post", + `${SERVICES_PATH}?mcp_service_id=${encodeURIComponent(name)}&parent=${encodeURIComponent(`schemas/${catalog}.${schema}`)}`, + { body: { config }, profile }, + ); + } + } catch (err) { + if (err instanceof DatabricksApiError && FLAG_OFF.test(err.message)) { + throw new Error( + `This workspace does not support App sources for MCP Services: the flag databricks.unitycatalog.aigov.enableMcpAppSource is off. Use a workspace where it is on.\n${err.message}`, + ); + } + throw err; + } + console.log( + `${exists ? "Updated" : "Created"} MCP Service ${fqn} -> app ${app}.`, + ); + + for (const principal of opts.grant) { + await databricksApi( + "patch", + `/api/2.1/unity-catalog/permissions/mcp_service/${fqn}`, + { + body: { changes: [{ principal, add: ["EXECUTE"] }] }, + profile, + }, + ); + await databricksApi("patch", `/api/2.0/permissions/apps/${app}`, { + body: { + access_control_list: [ + { + [principalField(principal)]: principal, + permission_level: "CAN_USE", + }, + ], + }, + profile, + }); + console.log( + `Granted EXECUTE on ${fqn} and CAN_USE on app ${app} to ${principal}.`, + ); + } + + console.log( + `Unity Gateway URL: ${await workspaceHost(profile)}/ai-gateway/mcp-services/${fqn}`, + ); + } catch (err) { + console.error(err instanceof Error ? err.message : String(err)); + process.exitCode = 1; + } + }); diff --git a/packages/shared/src/cli/commands/mcp/unregister.ts b/packages/shared/src/cli/commands/mcp/unregister.ts new file mode 100644 index 000000000..b845cad5d --- /dev/null +++ b/packages/shared/src/cli/commands/mcp/unregister.ts @@ -0,0 +1,18 @@ +import { Command } from "commander"; + +import { databricksApi, parseFqn, SERVICES_PATH } from "./databricks-cli"; + +export const mcpUnregisterCommand = new Command("unregister") + .description("Delete the MCP Service; the App is left running") + .argument("", "MCP Service name: ..") + .option("--profile ", "Databricks CLI profile") + .action(async (fqn: string, opts: { profile?: string }) => { + try { + parseFqn(fqn); + await databricksApi("delete", `${SERVICES_PATH}/${fqn}`, opts); + console.log(`Deleted MCP Service ${fqn}.`); + } catch (err) { + console.error(err instanceof Error ? err.message : String(err)); + process.exitCode = 1; + } + }); diff --git a/packages/shared/src/cli/index.ts b/packages/shared/src/cli/index.ts index af8c22e6e..717033cb3 100644 --- a/packages/shared/src/cli/index.ts +++ b/packages/shared/src/cli/index.ts @@ -12,6 +12,7 @@ import { docsCommand } from "./commands/docs.js"; import { doctorCommand } from "./commands/doctor/index.js"; import { generateTypesCommand } from "./commands/generate-types.js"; import { lintCommand } from "./commands/lint.js"; +import { mcpCommand } from "./commands/mcp/index.js"; import { pluginCommand } from "./commands/plugin/index.js"; import { addCommand } from "./commands/registry/add.js"; import { registryCommand } from "./commands/registry/index.js"; @@ -40,6 +41,7 @@ cmd.addCommand(doctorCommand); cmd.addCommand(registryCommand, { hidden: true }); cmd.addCommand(addCommand, { hidden: true }); cmd.addCommand(agentCommand); +cmd.addCommand(mcpCommand); // Surface a clean message for any uncaught setup failure (e.g. a root // evals.config.ts that throws on import) instead of a raw unhandled-rejection From ed3ecd67ae09fcca44f15b00c01b2a2045f1e83f Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Wed, 2 Dec 2026 22:31:27 +0000 Subject: [PATCH 2/3] chore: re-run the check now that pnpm is on the check shell's PATH No code change: the previous check failed with `pnpm: not found` because corepack's pnpm shim was not enabled on the check machine. Signed-off-by: mario.cadenas Co-authored-by: Isaac From f6688d64c30ce466a0ef75b0363aaedba2ff9d77 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Wed, 2 Dec 2026 22:52:33 +0000 Subject: [PATCH 3/3] fix(appkit): keep MCP service limits on re-register and encode names - Re-registering an existing MCP Service now carries over its include_tool_selectors and rate_limits; `update_mask=config` replaces the whole config, so they were silently cleared before. - Service names are URL-encoded per part, so a `#` or `?` in the name can no longer truncate the path and hit a different service. - App names must be lowercase letters, digits and hyphens, which stops path tricks in the permissions URL and unresolved `${var...}` names from databricks.yml (the error says to pass --app). Signed-off-by: mario.cadenas Co-authored-by: Isaac --- docs/docs/development/mcp-register.md | 2 +- .../src/cli/commands/mcp/databricks-cli.ts | 8 +++ .../src/cli/commands/mcp/register.test.ts | 53 +++++++++++++++++-- .../shared/src/cli/commands/mcp/register.ts | 35 +++++++++--- .../shared/src/cli/commands/mcp/unregister.ts | 4 +- 5 files changed, 87 insertions(+), 15 deletions(-) diff --git a/docs/docs/development/mcp-register.md b/docs/docs/development/mcp-register.md index 8684d7bd6..5728ba396 100644 --- a/docs/docs/development/mcp-register.md +++ b/docs/docs/development/mcp-register.md @@ -20,7 +20,7 @@ npx @databricks/appkit mcp register main.default.my_app --app my-app \ - `--grant ` (repeatable): grants `EXECUTE` on the MCP Service and `CAN_USE` on the app. A principal containing `@` is a user, a UUID is a service principal (application ID), anything else is a group. Existing app permissions are kept. - `--profile `: Databricks CLI profile, passed to every `databricks` call. -The command prints the Unity Gateway URL to give MCP clients. `include_tool_selectors` is left unset; re-registering replaces the service's whole `config`, so any selectors set elsewhere are cleared. +The command prints the Unity Gateway URL to give MCP clients. A new service is created without `include_tool_selectors`. Re-registering an existing service only changes the app source and keeps its existing tool selectors and rate limits. ## Requirements diff --git a/packages/shared/src/cli/commands/mcp/databricks-cli.ts b/packages/shared/src/cli/commands/mcp/databricks-cli.ts index 805481c4d..b20bcd924 100644 --- a/packages/shared/src/cli/commands/mcp/databricks-cli.ts +++ b/packages/shared/src/cli/commands/mcp/databricks-cli.ts @@ -65,3 +65,11 @@ export function parseFqn(fqn: string): string { } export const SERVICES_PATH = "/api/2.1/unity-catalog/mcp-services"; + +/** Each part is encoded so a `#`, `?` or `/` in a name can't truncate or retarget the request. */ +export function encodeFqn(fqn: string): string { + return fqn.split(".").map(encodeURIComponent).join("."); +} + +export const servicePath = (fqn: string) => + `${SERVICES_PATH}/${encodeFqn(fqn)}`; diff --git a/packages/shared/src/cli/commands/mcp/register.test.ts b/packages/shared/src/cli/commands/mcp/register.test.ts index fcbefc849..17eceee85 100644 --- a/packages/shared/src/cli/commands/mcp/register.test.ts +++ b/packages/shared/src/cli/commands/mcp/register.test.ts @@ -73,21 +73,57 @@ describe("appkit mcp", () => { ); }); - it("updates with PATCH when the service exists", async () => { + it("updates with PATCH, keeping tool selectors and rate limits and dropping source_connection", async () => { respond = (args) => - args[0] === "auth" ? ok('{"details":{"host":"https://h"}}') : ok(); + args[0] === "auth" + ? ok('{"details":{"host":"https://h"}}') + : args[1] === "get" + ? ok( + JSON.stringify({ + config: { + source_connection: { name: "c", options: {} }, + include_tool_selectors: [{ name: "t" }], + rate_limits: [{ calls: 5 }], + }, + }), + ) + : ok(); await run("register", FQN, "--app", "my-app"); expect(api("post")).toHaveLength(0); const [patch] = api("patch"); expect(patch[2]).toBe( `/api/2.1/unity-catalog/mcp-services/${FQN}?update_mask=config`, ); - expect(body(patch).config.source_app).toEqual({ - name: "my-app", - mcp_path: "/mcp", + expect(body(patch)).toEqual({ + config: { + source_app: { name: "my-app", mcp_path: "/mcp" }, + include_tool_selectors: [{ name: "t" }], + rate_limits: [{ calls: 5 }], + }, }); }); + it("rejects invalid app names (including unresolved bundle variables) without calling databricks", async () => { + await run("register", FQN, "--app", "../../sql/x?y="); + expect(errLog.mock.calls[0][0]).toContain( + 'Invalid app name "../../sql/x?y="', + ); + const dir = fs.mkdtempSync( + path.join(process.env.TMPDIR ?? os.tmpdir(), "mcp-"), + ); + fs.writeFileSync( + path.join(dir, "databricks.yml"), + "resources:\n apps:\n a:\n name: ${var.app_name}\n", + ); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + await run("register", FQN); + cwd.mockRestore(); + fs.rmSync(dir, { recursive: true }); + expect(errLog.mock.calls[1][0]).toContain("pass --app "); + expect(calls).toHaveLength(0); + expect(process.exitCode).toBe(1); + }); + it("grants EXECUTE on the service and CAN_USE on the app per principal", async () => { await run( "register", @@ -203,6 +239,13 @@ describe("appkit mcp", () => { expect(process.exitCode).toBe(1); }); + it("unregister encodes the name so a # cannot truncate the path", async () => { + await run("unregister", "a.b.c#x"); + expect(calls).toEqual([ + ["api", "delete", "/api/2.1/unity-catalog/mcp-services/a.b.c%23x"], + ]); + }); + it("unregister deletes only the service", async () => { await run("unregister", FQN, "--profile", "dev"); expect(calls).toEqual([ diff --git a/packages/shared/src/cli/commands/mcp/register.ts b/packages/shared/src/cli/commands/mcp/register.ts index ed408ff56..a479810fc 100644 --- a/packages/shared/src/cli/commands/mcp/register.ts +++ b/packages/shared/src/cli/commands/mcp/register.ts @@ -10,6 +10,8 @@ import { databricksApi, parseFqn, SERVICES_PATH, + encodeFqn, + servicePath, workspaceHost, } from "./databricks-cli"; @@ -70,24 +72,43 @@ export const mcpRegisterCommand = new Command("register") try { parseFqn(fqn); const app = opts.app ?? appFromBundle(process.cwd()); + if (!/^[a-z0-9-]+$/.test(app)) { + throw new Error( + `Invalid app name "${app}": app names are lowercase letters, digits and hyphens.${ + app.includes("${") + ? " Bundle variables aren't resolved here; pass --app ." + : "" + }`, + ); + } const { profile } = opts; const [catalog, schema, name] = fqn.split("."); const config = { source_app: { name: app, mcp_path: "/mcp" } }; - const url = `${SERVICES_PATH}/${fqn}`; + const url = servicePath(fqn); - const exists = await databricksApi("get", url, { profile }).then( - () => true, + const existing = await databricksApi("get", url, { profile }).then( + (svc) => svc ?? {}, (err) => { if (err instanceof DatabricksApiError && NOT_FOUND.test(err.message)) - return false; + return undefined; throw err; }, ); + const exists = existing !== undefined; try { if (exists) { - // "config" replaces the whole config (source_app has no granular mask path). + // "config" replaces the whole config and drops omitted optional fields, so + // carry over the ones we don't manage; source_connection must not ride along. + const { include_tool_selectors, rate_limits } = existing.config ?? {}; + const merged = { + ...config, + ...(include_tool_selectors !== undefined && { + include_tool_selectors, + }), + ...(rate_limits !== undefined && { rate_limits }), + }; await databricksApi("patch", `${url}?update_mask=config`, { - body: { config }, + body: { config: merged }, profile, }); } else { @@ -113,7 +134,7 @@ export const mcpRegisterCommand = new Command("register") for (const principal of opts.grant) { await databricksApi( "patch", - `/api/2.1/unity-catalog/permissions/mcp_service/${fqn}`, + `/api/2.1/unity-catalog/permissions/mcp_service/${encodeFqn(fqn)}`, { body: { changes: [{ principal, add: ["EXECUTE"] }] }, profile, diff --git a/packages/shared/src/cli/commands/mcp/unregister.ts b/packages/shared/src/cli/commands/mcp/unregister.ts index b845cad5d..6975bc768 100644 --- a/packages/shared/src/cli/commands/mcp/unregister.ts +++ b/packages/shared/src/cli/commands/mcp/unregister.ts @@ -1,6 +1,6 @@ import { Command } from "commander"; -import { databricksApi, parseFqn, SERVICES_PATH } from "./databricks-cli"; +import { databricksApi, parseFqn, servicePath } from "./databricks-cli"; export const mcpUnregisterCommand = new Command("unregister") .description("Delete the MCP Service; the App is left running") @@ -9,7 +9,7 @@ export const mcpUnregisterCommand = new Command("unregister") .action(async (fqn: string, opts: { profile?: string }) => { try { parseFqn(fqn); - await databricksApi("delete", `${SERVICES_PATH}/${fqn}`, opts); + await databricksApi("delete", servicePath(fqn), opts); console.log(`Deleted MCP Service ${fqn}.`); } catch (err) { console.error(err instanceof Error ? err.message : String(err));