Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/setup-mcp-client-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@zitadel/cli": minor
---

`zitadel setup` writes `.mcp.json` at the app's root, so Claude Code and the Copilot agent in VS Code started in the app are connected to the server's MCP endpoint (`/api/v1/mcp`) without a further step. The committed file holds no secret: Claude Code reads the project secret from the git-ignored `.zitadel/secret` through the file's `headersHelper`, and VS Code fills `${ZITADEL_PROJECT_SECRET}` from its environment. Setup adds its server beside the servers a `.mcp.json` already names, and leaves alone one that already names `zitadel`.
14 changes: 14 additions & 0 deletions apps/cli/skills/zitadel-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,20 @@ is not ignored, and warns when `.env.example` is, as an older setup left
SvelteKit, Nuxt and SolidStart apps; `doctor --fix` appends `!.env.example`
while the file names variables without values.

`setup` also writes `.mcp.json` at the app's root, the file Claude Code and
the Copilot agent in VS Code read: the server `zitadel` at the server's MCP
endpoint, `<server>/api/v1/mcp`, whose tools are the API's operations. The
file is committed and holds no secret: its `headersHelper` reads the project
secret from `.zitadel/secret` for Claude Code, and its `headers` name
`${ZITADEL_PROJECT_SECRET}` for a client that fills it from its environment.
Setup adds its server to a `.mcp.json` that names others, keeping their entries,
and leaves alone one that already names `zitadel` or is not a JSON object, so
`data.files_written` lists the file only when setup changed it. It writes
none for `--server mock`. A session the developer starts in the app later
sees the endpoint's tools once they approve the server. You have a shell, so
keep using the CLI: `api <operationId>` calls the same operations and its
output costs your context less.

In an app that already exists, `setup` adds the sign-in, sign-up and profile
pages and the protection for the pages it guards, and leaves the app's own
pages as they are. Read the app's pages afterwards and add what the developer
Expand Down
45 changes: 42 additions & 3 deletions apps/cli/src/lib/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,34 @@ export function setTopLevelJsonKey(
path: string,
key: string,
value: unknown,
): string {
return setJsonValue(source, path, [key], value);
}

/**
* {@link setTopLevelJsonKey} for a value under nested keys: `["mcpServers",
* "zitadel"]` sets `zitadel` inside the top-level `mcpServers`, creating
* `mcpServers` when the document has none. Every key above the last must name
* an object or nothing, or the edit throws.
*
* @param source - The document's text.
* @param path - The file's name, for the error.
* @param keys - The keys to the value, outermost first; at least one.
* @param value - The value to set.
* @returns The document's text with the value set.
* @throws {Error} When the document is no JSON object, or the edit does not
* verify.
*/
export function setJsonValue(
source: string,
path: string,
keys: readonly [string, ...string[]],
value: unknown,
): string {
const parsed = parseJsonObject(source, path);
const indent = detectIndent(source);
const compact = indent === 0;
const edits = modify(source, [key], value, {
const edits = modify(source, [...keys], value, {
// A compact document gets no formatting, so the value goes in on one line.
formattingOptions: compact
? undefined
Expand All @@ -57,13 +80,29 @@ export function setTopLevelJsonKey(
const next = applyEdits(source, edits);

const verification = parseJsonObject(next, path);
const expected = { ...parsed, [key]: value };
if (JSON.stringify(verification) !== JSON.stringify(expected)) {
if (JSON.stringify(verification) !== JSON.stringify(withValueAt(parsed, keys, value))) {
throw new Error(`refusing to write ${path}: the targeted JSON edit did not verify`);
}
return next;
}

/**
* @param target - The value to set the value in. It is not changed.
* @param keys - The keys to the value, outermost first.
* @param value - The value.
* @returns `value` when no key is left, else a copy of `target` with `value`
* at `keys`, every object on the way copied and a missing one created, as
* `modify` does it.
*/
function withValueAt(target: unknown, keys: readonly string[], value: unknown): unknown {
const [key, ...rest] = keys;
if (key === undefined) {
return value;
}
const object = isObject(target) ? target : {};
return { ...object, [key]: withValueAt(object[key], rest, value) };
}

/**
* Infers the indentation unit of a JSON document: the whitespace prefix of
* its first indented line, a compact document stays compact (`0`), and
Expand Down
6 changes: 4 additions & 2 deletions apps/cli/src/lib/orca/patchers/rule/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type {
PatchResult,
PatchView,
} from "@/lib/orca/patchers/types";
import { mcpClientOps } from "./mcp-client";
import { reclaimableOps, withoutExistingTargets } from "./reclaim";
import { Project } from "@/lib/project";

Expand Down Expand Up @@ -431,8 +432,8 @@ export abstract class AbstractRulePatcher implements Patcher {

/**
* The framework-agnostic `.zitadel/` base files every rule patcher writes:
* the project secret, `zitadel.json`, env templates, and an empty sync
* state. The `schemas/` and `flows/` directories are created empty here;
* the project secret, `zitadel.json`, env templates, an empty sync state,
* the guidance sections and the MCP client's `.mcp.json`. The `schemas/` and `flows/` directories are created empty here;
* setup fills them from versioned local defaults after patching.
* Pure: no filesystem or network.
*/
Expand Down Expand Up @@ -509,6 +510,7 @@ export abstract class AbstractRulePatcher implements Patcher {
contents: `${stableStringify({ framework: ctx.framework.id })}\n`,
},
...guidanceOps(ctx),
...mcpClientOps(ctx.server),
];
}

Expand Down
9 changes: 8 additions & 1 deletion apps/cli/src/lib/orca/patchers/rule/guidance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/
import type { PatchContext } from "@/lib/orca/patchers/types";
import { Spelling } from "@/lib/suggestion";
import { MCP_CONFIG_FILE, MCP_SERVER_NAME, mcpEndpointOf } from "./mcp-client";

const MARKER_BEGIN = "<!-- zitadel:guidance:begin -->";
const MARKER_END = "<!-- zitadel:guidance:end -->";
Expand Down Expand Up @@ -97,6 +98,12 @@ export function agentsGuidanceSection(ctx: PatchContext): string {
// app that protects a checkout cannot tell whether the visitor returns to it.
const returnPathParagraph =
"After sign-in the login goes to the path in its page's `?next=` parameter, ahead of `post-sign-in-url`, so a visitor a protected route sent to sign in lands back on that route; a page of your own can read `next` to tell them why they must sign in. Set `force-post-sign-in-url` (SDK wrappers: `forcePostSignInUrl`) on a login whose page uses `next` for something else.";
// The endpoint is the server's, so a project on the mock server has none.
const endpoint = mcpEndpointOf(ctx.server);
const mcpParagraph =
endpoint === undefined
? ""
: `\n\nAn MCP client started in this directory is connected to the project through \`${MCP_CONFIG_FILE}\`, as the server \`${MCP_SERVER_NAME}\`: the server's endpoint ${endpoint}, which offers each operation of the API as a tool and asks the person before a call that deletes, revokes, rolls back or deploys. Claude Code reads the project secret from \`.zitadel/secret\` through the file's \`headersHelper\`, once you trust the folder; the Copilot agent in VS Code sends \`ZITADEL_PROJECT_SECRET\` from the environment it was started in. With a shell, the CLI does the same work and costs the context less.`;
return `## Authentication (Zitadel)

This app's login is managed by Zitadel. Local config is the source of truth for what the login collects and how sign-in works (step 3 below). The app files setup generated are yours to change, from the pages to the request boundary that protects routes in a server-rendered app: \`doctor\` reports a file you changed as \`edited\`, or as \`adopted\` once you delete its \`zitadel-cli: managed-file\` comment, and \`doctor --fix\` restores only a missing file, never one you changed.
Expand All @@ -120,7 +127,7 @@ ${themingParagraph}

${sessionStateParagraph}

${returnPathParagraph}
${returnPathParagraph}${mcpParagraph}

Machine-readable dialect (read these before authoring flow or schema edits):

Expand Down
136 changes: 136 additions & 0 deletions apps/cli/src/lib/orca/patchers/rule/mcp-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* The MCP client configuration setup writes beside the app (ADR 092, open
* question 1): a root `.mcp.json`, the file Claude Code and the Copilot agent
* in VS Code read, naming the server's MCP endpoint, so that a coding agent
* started in the project is connected to the project with no step of its own.
*
* The file is committed, so it holds no secret. Claude Code takes the bearer
* from `headersHelper`, a command it runs in the project's directory once the
* person trusted the folder, which reads the project secret from the
* git-ignored `.zitadel/secret`. VS Code runs no helper: it sends `headers`,
* whose `${ZITADEL_PROJECT_SECRET:-}` it fills from the environment it was
* started in. Where both apply, the helper's header replaces the static one.
*
* A configuration someone wrote stays as it is: setup adds its server to a
* file that names no server of that name, and leaves alone a file it cannot
* read as JSON.
*/
import { apiBaseUrl } from "@/lib/backend/transport";
import { isObject, parseJsonOrUndefined, setJsonValue } from "@/lib/json";
import type { FileOp } from "./file-writer/types";

/** The file setup writes, at the project's root. */
export const MCP_CONFIG_FILE = ".mcp.json";

/** The name the endpoint is configured under: a client's tools are `mcp__zitadel__…`. */
export const MCP_SERVER_NAME = "zitadel";

/**
* The command Claude Code runs for the endpoint's headers: it prints the
* project secret of `.zitadel/secret` as a bearer, as the JSON object of
* headers Claude Code reads from it. Node is there in every app setup
* supports, and it runs in the directory `.mcp.json` is in.
*/
export const MCP_HEADERS_HELPER =
"node -p \"JSON.stringify({Authorization:'Bearer '+JSON.parse(require('fs').readFileSync('.zitadel/secret','utf8')).project_secret})\"";

/**
* The header a client that runs no helper sends: the project secret, from the
* environment it was started in. The CLI and the app read the same variable.
* Its empty default keeps Claude Code, whose helper's header replaces this
* one, from warning about a variable it does not need.
*/
const STATIC_AUTHORIZATION = "Bearer ${ZITADEL_PROJECT_SECRET:-}";

/** The server entry setup writes, in the order a person reads it. */
type McpServerEntry = Readonly<{
type: "http";
url: string;
headers: Readonly<{ Authorization: string }>;
headersHelper: string;
}>;

/**
* @param server - The server setup created the project on.
* @returns The endpoint's URL on it, or `undefined` for a server that is not
* one (`mock`), which has no endpoint to connect to.
*/
export function mcpEndpointOf(server: string): string | undefined {
if (!URL.canParse(server)) {
return undefined;
}
const { protocol } = new URL(server);
if (protocol !== "http:" && protocol !== "https:") {
return undefined;
}
return `${apiBaseUrl(server)}/mcp`;
}

/**
* @param url - The endpoint's URL.
* @returns The entry that connects a client to it.
*/
export function mcpServerEntry(url: string): McpServerEntry {
return {
type: "http",
url,
headers: { Authorization: STATIC_AUTHORIZATION },
headersHelper: MCP_HEADERS_HELPER,
};
}

/**
* Adds the endpoint to an MCP client's configuration, leaving everything the
* file already says as it is.
*
* @remarks
* Only a missing entry is added: a file that already names a server
* `zitadel`, whatever it says, was written by someone, perhaps setup on an
* earlier run, and is theirs. A file that is no JSON object, or whose
* `mcpServers` is no object, is left as it is too: setup does not rewrite what
* it cannot read. Pure and idempotent, so the file-writer writes nothing when
* the answer is the source.
*
* @param source - The file's text, or `undefined` when there is none.
* @param url - The endpoint's URL.
* @returns The file's text with the endpoint configured.
*/
export function upsertMcpServer(source: string | undefined, url: string): string {
const entry = mcpServerEntry(url);
if (source === undefined || source.trim() === "") {
return `${JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: entry } }, null, 2)}\n`;
}
const parsed = parseJsonOrUndefined(source);
if (!isObject(parsed)) {
return source;
}
const servers = parsed.mcpServers;
if (servers !== undefined && !isObject(servers)) {
return source;
}
if (servers !== undefined && MCP_SERVER_NAME in servers) {
return source;
}
return setJsonValue(source, MCP_CONFIG_FILE, ["mcpServers", MCP_SERVER_NAME], entry);
}

/**
* @param server - The server setup created the project on.
* @returns The edit that configures the endpoint for an MCP client, or none
* for a server without one.
*/
export function mcpClientOps(server: string): FileOp[] {
const url = mcpEndpointOf(server);
if (url === undefined) {
return [];
}
return [
{
kind: "edit",
path: MCP_CONFIG_FILE,
edit: (source) => {
return upsertMcpServer(source, url);
},
},
];
}
10 changes: 10 additions & 0 deletions apps/cli/tests/helpers/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,11 @@ class CommittedFiles {
return this.read(".zitadel/branding/branding.json");
}

/** The MCP client's configuration, as the developer commits it, as text. */
mcpConfig(): Promise<string> {
return readFile(join(this.root, ".mcp.json"), "utf8");
}

/** Every committed configuration document as one string. */
async asText(slug: string): Promise<string> {
const documents = await Promise.all([
Expand Down Expand Up @@ -2299,6 +2304,11 @@ export class ScaffoldedApp {
return this.hasProjectFile("zitadel.json");
}

/** Writes the MCP client's configuration, as a developer who configured one by hand would. */
writeMcpConfig(contents: string): Promise<void> {
return this.writeProjectFile(".mcp.json", contents);
}

/** Writes `zitadel.json`, for a spec arranging a particular configuration. */
writeConfig(config: Record<string, unknown>): Promise<void> {
return this.writeProjectFile("zitadel.json", JSON.stringify(config, null, 2));
Expand Down
Loading
Loading