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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1592,3 +1592,25 @@ CLI session and cancel only the matching later steer. They do not cancel normal
queued prompts or interrupt unrelated current turns. Repeated exact Stop frames
send one physical interrupt. This intent does not survive a fresh CLI process;
steering is not automatically replayed offline.

### SDK MCP configuration

`heyditto mcp-config --session <id>` emits HTTP MCP server JSON for a trusted
SDK host. It selects the repository's `.ditto/` default endpoint, including its
Backroom tools, before the personal default; `--endpoint` overrides both.
It requires an existing CLI login and never opens an interactive picker.
The JSON contains an endpoint key that expires in one hour: pipe it directly
to the host, never save it in a project or include it in logs. Refresh before
subsequent turns; a single turn longer than an hour may need to be restarted.
Each export creates a fresh expiring key. Failed catalog exports revoke it.

With a T3 build that supports the Cursor SDK configuration hook, set this in
**the T3 server environment**, then restart that service and create a new
Cursor thread:

```sh
T3CODE_CURSOR_MCP_CONFIG_COMMAND='["heyditto","mcp-config"]'
```

T3 supplies `T3CODE_THREAD_ID` and runs the command in the thread's directory.
This hook does not invoke `heyditto cursor` or change Cursor's user settings.
59 changes: 59 additions & 0 deletions src/agents/mcp-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Command } from "commander";
import { createKey, findEndpoint, listEndpoints, revokeKey, type InferenceEndpoint } from "../api.js";
import { explicitProfileEndpoint, readDefaultEndpoint } from "../profiles.js";
import { findProfileEndpoint, repoDefaultProfile } from "../dittoconfig/profiles.js";
import { SESSION_ID_PATTERN } from "../mcp-session.js";
import { claudeMcpAttachment, fetchMcpCatalog, mcpUnavailableLines, type McpCatalog } from "./claude-mcp.js";

/** SDKs need concrete headers, unlike CLI configs that expand environment variables. */
export function sdkMcpConfig(catalog: McpCatalog, sessionId: string, apiKey: string) {
const attachment = claudeMcpAttachment(catalog, sessionId);
if (attachment.skipped.length) throw new Error("MCP catalog contains unsupported server names");
return { mcpServers: Object.fromEntries(attachment.attached.map(server => [server.name, {
type: "http" as const,
url: server.url,
headers: { Authorization: `Bearer ${apiKey}`, ...server.headers },
}])) };
}

export async function exportMcpConfig(options: { endpoint?: string; session?: string }): Promise<void> {
const sessionId = options.session ?? process.env.T3CODE_THREAD_ID;
if (!sessionId || !SESSION_ID_PATTERN.test(sessionId)) throw new Error("mcp-config needs --session or T3CODE_THREAD_ID");
const { endpoints, baseUrl } = await listEndpoints();
const explicit = options.endpoint?.trim() || (await explicitProfileEndpoint())?.endpoint;
let endpoint: InferenceEndpoint | undefined;
if (explicit) {
endpoint = findEndpoint(endpoints, explicit);
if (!endpoint) throw new Error(`No endpoint named "${explicit}"`);
} else {
const profile = await repoDefaultProfile(process.cwd());
if (profile) {
endpoint = await findProfileEndpoint(profile, endpoints);
if (!endpoint) throw new Error("Repository .ditto profile has no applied endpoint; run heyditto repo apply");
} else {
const saved = await readDefaultEndpoint();
endpoint = saved ? findEndpoint(endpoints, saved) : endpoints.length === 1 ? endpoints[0] : undefined;
}
}
if (!endpoint) throw new Error("No unambiguous MCP endpoint; select one with --endpoint or heyditto endpoints use");
const key = await createKey(endpoint.id, { name: `sdk-mcp:${sessionId}`, expiresIn: "1h" });
if (!key.key) throw new Error("MCP key response did not contain a key");
try {
const catalog = await fetchMcpCatalog(baseUrl, key.key, sessionId);
for (const line of mcpUnavailableLines(catalog)) process.stderr.write(`${line}\n`);
process.stdout.write(`${JSON.stringify(sdkMcpConfig(catalog, sessionId, key.key))}\n`);
} catch (error) {
await revokeKey(endpoint.id, key.id).catch(() => {
process.stderr.write(`warning: could not revoke MCP key ${key.id}; it may remain valid until its one-hour expiry\n`);
});
throw error;
}
}

export function registerMcpConfigCommand(program: Command): void {
program.command("mcp-config")
.description("emit credential-bearing SDK MCP JSON to a trusted parent process (keys expire in one hour)")
.option("--endpoint <endpoint>", "override repository .ditto and personal defaults")
.option("--session <id>", "session id (default: T3CODE_THREAD_ID)")
.action(exportMcpConfig);
}
2 changes: 2 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { registerConfigCommands } from "./dittoconfig/commands.js";
import { deviceLogin } from "./device-login.js";
import { registerSelfUpdateCommands } from "./self-update.js";
import { registerRelayCommands } from "./relay/commands.js";
import { registerMcpConfigCommand } from "./agents/mcp-config.js";
import { registerT3Commands } from "./t3/setup.js";
import { addProfileOption, installProfileHook, registerProfileCommands, selectedProfile } from "./profiles.js";

Expand Down Expand Up @@ -1344,6 +1345,7 @@ your own workspace or an app workspace.`,
registerHarnessCommands(program, addExamples);
registerRelayCommands(program);
registerT3Commands(program);
registerMcpConfigCommand(program);
registerCodexAppCommand(program, addExamples);
registerSessionCommands(program, addExamples);
registerTeleportCommands(program, addExamples);
Expand Down
89 changes: 89 additions & 0 deletions test/mcp-config.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sdkMcpConfig } from "../dist/agents/mcp-config.js";

test("SDK config exports Ditto and project Backroom with concrete credentials and session", () => {
const config = sdkMcpConfig({ endpoint: "sn118", approvalMode: "park", clientApprovals: true, servers: [
{ name: "ditto", url: "https://router.test/mcp/ditto", tools: [{ name: "search_memories", tier: "read", approval: false }] },
{ name: "backroom", url: "https://router.test/mcp/backroom", tools: [{ name: "list_screenings", tier: "read", approval: true }] },
] }, "fresh-thread", "synthetic-key");
assert.deepEqual(Object.keys(config.mcpServers), ["ditto", "ditto-backroom"]);
assert.equal(config.mcpServers["ditto-backroom"].headers.Authorization, "Bearer synthetic-key");
assert.equal(config.mcpServers.ditto.headers["X-Ditto-Session-Id"], "fresh-thread");
});

import { spawn } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

test("mcp-config selects .ditto Backroom endpoint in cwd, overrides explicitly, and revokes failed exports", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "mcp-sdk-"));
const requests = [];
let failCatalog = false;
let failRevoke = false;
const server = http.createServer((req, res) => {
requests.push([req.method, req.url]);
res.setHeader("content-type", "application/json");
const base = `http://127.0.0.1:${server.address().port}`;
if (req.url === "/api/v5/companies") return res.end(JSON.stringify({companies:[]}));
if (req.url === "/api/v5/inference/endpoints") return res.end(JSON.stringify({baseUrl:base+"/v1", endpoints:[
{id:"project",slug:"sn118",model:"native",status:"active"}, {id:"personal",slug:"other",model:"native",status:"active"},
]}));
if (req.method === "POST" && req.url.endsWith("/keys")) return res.end(JSON.stringify({id:"test-key",key:"synthetic-key"}));
if (req.method === "DELETE") {
if (failRevoke) res.statusCode = 503;
return res.end("{}");
}
if (req.url === "/v1/mcp") {
if (failCatalog) { res.statusCode = 503; return res.end("{}"); }
return res.end(JSON.stringify({endpoint:"sn118",approvalMode:"park",clientApprovals:false,servers:[
{name:"ditto",url:base+"/mcp/ditto",tools:[{name:"search_memories",tier:"read",approval:false}]},
{name:"backroom",url:base+"/mcp/backroom",tools:[{name:"list_screenings",tier:"read",approval:false}]},
]}));
}
res.statusCode = 404; res.end("{}");
});
await new Promise(resolve => server.listen(0,"127.0.0.1",resolve));
try {
await mkdir(path.join(dir,".ditto/endpoints"),{recursive:true});
await writeFile(path.join(dir,".ditto/config.toml"),'version = 1\n[repository]\nname = "subnet"\ndefault_endpoint = "dev"\n');
await writeFile(path.join(dir,".ditto/endpoints/dev.toml"),'managed = true\nname = "dev"\nslug = "sn118"\nmodel = "native"\n');
const run = (args=[]) => new Promise((resolve,reject) => {
const child = spawn(process.execPath,[fileURLToPath(new URL("../dist/cli.js",import.meta.url)),"mcp-config",...args],{
cwd:dir,env:{...process.env,DITTO_API_BASE:`http://127.0.0.1:${server.address().port}`,DITTO_API_KEY:"synthetic-login",DITTO_CONFIG_DIR:path.join(dir,"config"),DITTO_CLI_AUTO_UPDATE:"0",T3CODE_THREAD_ID:"fresh-thread"},stdio:["ignore","pipe","pipe"],
});
let stdout="",stderr="";
child.stdout.on("data",b=>stdout+=b);child.stderr.on("data",b=>stderr+=b);
child.on("error",reject);child.on("close",code=>resolve({code,stdout,stderr}));
});
const result = await run();
assert.equal(result.code,0,result.stderr);
assert.deepEqual(Object.keys(JSON.parse(result.stdout).mcpServers),["ditto","ditto-backroom"]);
assert.ok(requests.some(([method,url])=>method==="POST"&&url==="/api/v5/inference/endpoints/project/keys"));
const override = await run(["--endpoint","other"]);
assert.equal(override.code,0,override.stderr);
assert.ok(requests.some(([method,url])=>method==="POST"&&url==="/api/v5/inference/endpoints/personal/keys"));
const createdBeforeUnknown = requests.filter(([method]) => method === "POST").length;
const unknown = await run(["--endpoint", "missing-endpoint"]);
assert.notEqual(unknown.code, 0);
assert.equal(unknown.stdout, "");
assert.match(unknown.stderr, /No endpoint named "missing-endpoint"/);
assert.equal(requests.filter(([method]) => method === "POST").length, createdBeforeUnknown);
failCatalog = true;
const failed = await run();
assert.notEqual(failed.code,0);
assert.equal(failed.stdout,"");
assert.ok(requests.some(([method,url])=>method==="DELETE"&&url==="/api/v5/inference/endpoints/project/keys/test-key"));
assert.doesNotMatch(failed.stderr, /could not revoke MCP key/);
failRevoke = true;
const unrevoked = await run();
assert.notEqual(unrevoked.code, 0);
assert.equal(unrevoked.stdout, "");
assert.match(unrevoked.stderr, /could not revoke MCP key test-key; it may remain valid until its one-hour expiry/);
assert.match(unrevoked.stderr, /503/);
assert.doesNotMatch(unrevoked.stderr, /synthetic-key/);
} finally { server.closeAllConnections(); await new Promise(resolve=>server.close(resolve)); await rm(dir,{recursive:true,force:true}); }
});