Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/docs/development/mcp-register.md
Original file line number Diff line number Diff line change
@@ -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 `<workspace host>/ai-gateway/mcp-services/<catalog.schema.name>`. 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
```

- `<catalog.schema.name>`: the MCP Service to create, or update if it already exists.
- `--app <name>`: the app to register. Defaults to the single app declared in `databricks.yml`.
- `--grant <principal>` (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 <profile>`: Databricks CLI profile, passed to every `databricks` call.

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

- `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.
75 changes: 75 additions & 0 deletions packages/shared/src/cli/commands/mcp/databricks-cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
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 <method> <path> [--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<any> {
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<string> {
const args = ["auth", "describe", "-o", "json"];
if (profile) args.push("--profile", profile);
const out = await new Promise<string>((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 <catalog>.<schema>.<name>.`,
);
}
return fqn;
}

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)}`;
13 changes: 13 additions & 0 deletions packages/shared/src/cli/commands/mcp/index.ts
Original file line number Diff line number Diff line change
@@ -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);
261 changes: 261 additions & 0 deletions packages/shared/src/cli/commands/mcp/register.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
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<typeof vi.spyOn>;
let errLog: ReturnType<typeof vi.spyOn>;
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, keeping tool selectors and rate limits and dropping source_connection", async () => {
respond = (args) =>
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)).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 <name>");
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",
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 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([
[
"api",
"delete",
`/api/2.1/unity-catalog/mcp-services/${FQN}`,
"--profile",
"dev",
],
]);
});
});
Loading
Loading