mirror of
https://github.com/penpot/penpot.git
synced 2026-10-03 09:16:15 +00:00
* 🎉 Add multi-file session routing to the MCP server Session routing: - Track each user's Penpot connections by session ID. - Dispatch explicit sessions directly; otherwise discover the sole session. - Return a retryable error when discovery fails or is incomplete. Plugin and tools: - Initialize connections with a fresh session ID and file metadata. - Share the optional sessionId schema and place it last in tool inputs. Validation: - 84 tests, server type checking, and MCP formatting checks pass. - Disable test logging to avoid the logging worker shutdown hang. AI-assisted-by: gpt-6 * 🎉 Support independent MCP connections - Require explicit connection intent for each integrated workspace. - Derive short session IDs from the Penpot app instance and file. - Show and copy session IDs in the MCP menu and standalone plugin UI. - Stop stale callbacks and reconnect attempts after disconnect. Validate with frontend and plugin tests, type checking, live multi-tab checks, and standalone UI checks with a simulated connection. Server tests pass with --test-force-exit; the normal runner can hang on shutdown. AI-assisted-by: gpt-6 * 📚 Document multi-file MCP sessions - Explain independent connections, session selection, and copying IDs. - Describe session ID lifetimes for integrated and standalone plugins. - Correct browser focus, connection, and recovery guidance. Validate with the documentation site build and diff checks. AI-assisted-by: gpt-6 * ✨ Change behavior on session ID duplication * ✨ Open MCP toolbar menu on hover and match menu style --------- Co-authored-by: alonso.torres <alonso.torres@kaleidos.net> Co-authored-by: elhombretecla <delacruzgarciajuan@gmail.com>
138 lines
5.0 KiB
TypeScript
138 lines
5.0 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { afterEach, beforeEach, test } from "node:test";
|
|
import { type CallToolResult, Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
import { PenpotMcpServer } from "./PenpotMcpServer";
|
|
|
|
let server: PenpotMcpServer;
|
|
let baseUrl: string;
|
|
let previousEnv: NodeJS.ProcessEnv;
|
|
let nextPort = 16_500;
|
|
|
|
beforeEach(async () => {
|
|
previousEnv = { ...process.env };
|
|
process.env.PENPOT_MCP_SERVER_HOST = "127.0.0.1";
|
|
process.env.PENPOT_MCP_SERVER_PORT = String(nextPort++);
|
|
process.env.PENPOT_MCP_WEBSOCKET_PORT = "0";
|
|
process.env.PENPOT_MCP_DEVENV = "false";
|
|
process.env.PENPOT_MCP_REPL_ENABLE = "false";
|
|
delete process.env.PENPOT_MCP_REDIS_URI;
|
|
server = new PenpotMcpServer(true);
|
|
baseUrl = `http://127.0.0.1:${server.port}`;
|
|
await server.start();
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await server?.stop();
|
|
process.env = previousEnv;
|
|
});
|
|
|
|
async function modernRequest(method: string, params: Record<string, unknown> = {}, query = "") {
|
|
return fetch(`${baseUrl}/mcp${query}`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Accept: "application/json, text/event-stream",
|
|
"MCP-Protocol-Version": "2026-07-28",
|
|
"Mcp-Method": method,
|
|
...(typeof params.name === "string" ? { "Mcp-Name": params.name } : {}),
|
|
},
|
|
body: JSON.stringify({
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
method,
|
|
params: {
|
|
...params,
|
|
_meta: {
|
|
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
|
"io.modelcontextprotocol/clientInfo": { name: "penpot-test", version: "1" },
|
|
"io.modelcontextprotocol/clientCapabilities": {},
|
|
},
|
|
},
|
|
}),
|
|
});
|
|
}
|
|
|
|
test("serves repeated modern client requests without allocating a session", async () => {
|
|
const client = new Client(
|
|
{ name: "modern-test", version: "1" },
|
|
{ versionNegotiation: { mode: { pin: "2026-07-28" } } }
|
|
);
|
|
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
|
|
try {
|
|
await client.connect(transport);
|
|
for (let i = 0; i < 2; i++) {
|
|
const result = await client.listTools();
|
|
assert.equal(transport.sessionId, undefined);
|
|
const tool = result.tools.find((tool) => tool.name === "execute_code");
|
|
assert.ok(tool);
|
|
assert.equal(tool.inputSchema.type, "object");
|
|
assert.deepEqual(tool.inputSchema.required, ["code"]);
|
|
}
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
});
|
|
|
|
test("isolates user tokens across overlapping tool calls with the same request ID", async (t) => {
|
|
let release!: () => void;
|
|
const bothStarted = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
let started = 0;
|
|
t.mock.method(server.pluginBridge, "executePluginTask", async () => {
|
|
if (++started === 2) release();
|
|
await bothStarted;
|
|
return { data: server.getSessionContext()?.userToken ?? null };
|
|
});
|
|
|
|
const results = await Promise.all(
|
|
["alice", "bob"].map(async (token) => {
|
|
const response = await modernRequest(
|
|
"tools/call",
|
|
{
|
|
name: "execute_code",
|
|
arguments: { code: "return 1;" },
|
|
},
|
|
`?userToken=${token}`
|
|
);
|
|
const body = (await response.json()) as { result: CallToolResult };
|
|
assert.equal(response.status, 200, JSON.stringify(body));
|
|
const content = body.result.content[0];
|
|
assert.equal(content.type, "text");
|
|
return JSON.parse(content.text);
|
|
})
|
|
);
|
|
assert.deepEqual(results, ["alice", "bob"]);
|
|
assert.equal(server.getSessionContext(), undefined);
|
|
});
|
|
|
|
test("passes an explicit Penpot session ID from the tool call to plugin dispatch", async (t) => {
|
|
t.mock.method(server.pluginBridge, "executePluginTask", async (_task: unknown, sessionId?: string) => ({
|
|
data: sessionId,
|
|
}));
|
|
const response = await modernRequest(
|
|
"tools/call",
|
|
{
|
|
name: "execute_code",
|
|
arguments: { code: "return penpot.currentFile.id;", sessionId: "chosen-tab" },
|
|
},
|
|
"?userToken=alice"
|
|
);
|
|
assert.equal(response.status, 200);
|
|
const body = await response.json();
|
|
assert.match(JSON.stringify(body), /chosen-tab/);
|
|
});
|
|
|
|
test("supports older Streamable HTTP clients without allocating a session", async () => {
|
|
const client = new Client({ name: "legacy-test", version: "1" });
|
|
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
|
|
try {
|
|
await client.connect(transport);
|
|
assert.equal(transport.sessionId, undefined);
|
|
const result = await client.listTools();
|
|
assert.ok(result.tools.some((tool) => tool.name === "execute_code"));
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
});
|