@comforge/mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +181 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +77 -0
- package/dist/contracts.d.ts +224 -0
- package/dist/contracts.js +400 -0
- package/dist/grants.d.ts +1 -0
- package/dist/grants.js +25 -0
- package/dist/host.d.ts +68 -0
- package/dist/host.js +78 -0
- package/dist/http.d.ts +37 -0
- package/dist/http.js +163 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/results.d.ts +80 -0
- package/dist/results.js +169 -0
- package/dist/server.d.ts +30 -0
- package/dist/server.js +195 -0
- package/dist/stdio.d.ts +17 -0
- package/dist/stdio.js +13 -0
- package/dist/tools.d.ts +40 -0
- package/dist/tools.js +510 -0
- package/llms.txt +33 -0
- package/package.json +37 -4
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the host gives the server, and the repository allowlist.
|
|
3
|
+
*
|
|
4
|
+
* Trust boundary: the host owns credentials, the runtime that runs repository commands, the
|
|
5
|
+
* state store and the principal. A caller supplies none of them: it names an allowlisted
|
|
6
|
+
* repository id, and the server resolves everything else from the host and from the
|
|
7
|
+
* repository's trusted configuration (its base branch, never the working tree).
|
|
8
|
+
*/
|
|
9
|
+
import { type ComforgeConfig, type CredentialProvider, type HostPolicy, type Runtime, type StateStore } from "@comforge/cli";
|
|
10
|
+
import type { Principal } from "./contracts.ts";
|
|
11
|
+
export interface RepositoryBinding {
|
|
12
|
+
/** Allowlisted id callers use. */
|
|
13
|
+
id: string;
|
|
14
|
+
/** Absolute path of the primary checkout. Never shown to, or taken from, a caller. */
|
|
15
|
+
root: string;
|
|
16
|
+
/** Git common directory; defaults to `<root>/.git`. */
|
|
17
|
+
commonDir?: string;
|
|
18
|
+
/** GitHub identity the trusted configuration must name. */
|
|
19
|
+
owner: string;
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Host-provided isolation for repository commands over a remote transport. The host
|
|
24
|
+
* attests that `runtime` runs every command inside an isolation boundary it operates
|
|
25
|
+
* (container, VM, dedicated worker). A flag cannot stand in for it: without a provider,
|
|
26
|
+
* executing tools are neither listed nor callable over HTTP.
|
|
27
|
+
*/
|
|
28
|
+
export interface IsolationProvider {
|
|
29
|
+
/** Non-secret identifier of the isolation, recorded in audit events and capabilities. */
|
|
30
|
+
readonly id: string;
|
|
31
|
+
runtime(binding: RepositoryBinding, principal: Principal): Runtime;
|
|
32
|
+
}
|
|
33
|
+
export interface AuditEvent {
|
|
34
|
+
tool: string;
|
|
35
|
+
principal: string;
|
|
36
|
+
repository: string | null;
|
|
37
|
+
outcome: "ok" | "refused" | "error";
|
|
38
|
+
code: string | null;
|
|
39
|
+
durationMs: number;
|
|
40
|
+
transport: "stdio" | "http";
|
|
41
|
+
}
|
|
42
|
+
export interface HostServices {
|
|
43
|
+
/** The runtime for read-only work and, on stdio, for repository commands. */
|
|
44
|
+
runtime(binding: RepositoryBinding): Runtime;
|
|
45
|
+
/** Server-owned credentials; never returned to a caller. Omit to use the configuration's source. */
|
|
46
|
+
credentials?(binding: RepositoryBinding, principal: Principal): CredentialProvider | undefined;
|
|
47
|
+
/** Shared initiative store; omit for the CLI's default, so the CLI and the server agree. */
|
|
48
|
+
state?(binding: RepositoryBinding): StateStore | undefined;
|
|
49
|
+
/** Called once per tool call, with no arguments, bodies or credentials. */
|
|
50
|
+
audit?(event: AuditEvent): void;
|
|
51
|
+
/**
|
|
52
|
+
* Trusted host policy for the lifecycle (checkout parent, worker preparation and removal,
|
|
53
|
+
* validation), per repository. Host code only: no tool input reaches it.
|
|
54
|
+
*/
|
|
55
|
+
hostPolicy?(binding: RepositoryBinding): HostPolicy | undefined;
|
|
56
|
+
}
|
|
57
|
+
/** Refuses an allowlist with duplicate or malformed ids, or relative paths. */
|
|
58
|
+
export declare function assertBindings(bindings: readonly RepositoryBinding[]): void;
|
|
59
|
+
export declare function resolveBinding(bindings: readonly RepositoryBinding[], principal: Principal, id: string): RepositoryBinding;
|
|
60
|
+
export declare const repositoryOf: (b: RepositoryBinding) => {
|
|
61
|
+
root: string;
|
|
62
|
+
commonDir: string;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* The configuration at the base branch's remote-tracking ref: what @comforge/cli trusts.
|
|
66
|
+
* The working tree's copy is ignored. It must name the binding's repository.
|
|
67
|
+
*/
|
|
68
|
+
export declare function trustedConfig(rt: Runtime, binding: RepositoryBinding): ComforgeConfig;
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the host gives the server, and the repository allowlist.
|
|
3
|
+
*
|
|
4
|
+
* Trust boundary: the host owns credentials, the runtime that runs repository commands, the
|
|
5
|
+
* state store and the principal. A caller supplies none of them: it names an allowlisted
|
|
6
|
+
* repository id, and the server resolves everything else from the host and from the
|
|
7
|
+
* repository's trusted configuration (its base branch, never the working tree).
|
|
8
|
+
*/
|
|
9
|
+
import { parseConfig, } from "@comforge/cli";
|
|
10
|
+
import { ToolRefusal } from "./results.js";
|
|
11
|
+
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
12
|
+
/** Refuses an allowlist with duplicate or malformed ids, or relative paths. */
|
|
13
|
+
export function assertBindings(bindings) {
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
for (const b of bindings) {
|
|
16
|
+
if (!ID.test(b.id))
|
|
17
|
+
throw new Error(`repository id ${JSON.stringify(b.id)} is malformed`);
|
|
18
|
+
if (seen.has(b.id))
|
|
19
|
+
throw new Error(`repository id ${b.id} is listed twice`);
|
|
20
|
+
seen.add(b.id);
|
|
21
|
+
if (!b.root.startsWith("/"))
|
|
22
|
+
throw new Error(`repository ${b.id}: root must be absolute`);
|
|
23
|
+
if (b.commonDir && !b.commonDir.startsWith("/"))
|
|
24
|
+
throw new Error(`repository ${b.id}: commonDir must be absolute`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function resolveBinding(bindings, principal, id) {
|
|
28
|
+
const binding = bindings.find((b) => b.id === id);
|
|
29
|
+
const allowed = principal.repositories === "*" || principal.repositories.includes(id);
|
|
30
|
+
// The same refusal whether the id is unknown or not the principal's: no allowlist probing.
|
|
31
|
+
if (!binding || !allowed)
|
|
32
|
+
throw new ToolRefusal("unknown-repository", `no repository ${id} for this principal`, 1, {
|
|
33
|
+
repository: id,
|
|
34
|
+
});
|
|
35
|
+
return binding;
|
|
36
|
+
}
|
|
37
|
+
export const repositoryOf = (b) => ({
|
|
38
|
+
root: b.root,
|
|
39
|
+
commonDir: b.commonDir ?? `${b.root}/.git`,
|
|
40
|
+
});
|
|
41
|
+
/**
|
|
42
|
+
* The configuration at the base branch's remote-tracking ref: what @comforge/cli trusts.
|
|
43
|
+
* The working tree's copy is ignored. It must name the binding's repository.
|
|
44
|
+
*/
|
|
45
|
+
export function trustedConfig(rt, binding) {
|
|
46
|
+
const read = (ref) => rt.run("git", ["show", `${ref}:comforge.config.json`], {
|
|
47
|
+
cwd: binding.root,
|
|
48
|
+
timeoutMs: 15_000,
|
|
49
|
+
});
|
|
50
|
+
// The base branch comes from the committed configuration itself, read at origin's HEAD
|
|
51
|
+
// first; a repository without one is refused like the CLI refuses it.
|
|
52
|
+
let r = read("refs/remotes/origin/HEAD");
|
|
53
|
+
if (r.status !== 0)
|
|
54
|
+
r = read("refs/remotes/origin/main");
|
|
55
|
+
if (r.status !== 0)
|
|
56
|
+
throw new ToolRefusal("config-missing", "the repository has no trusted comforge.config.json", 2, {
|
|
57
|
+
repository: binding.id,
|
|
58
|
+
});
|
|
59
|
+
let config;
|
|
60
|
+
try {
|
|
61
|
+
config = parseConfig(r.stdout, "comforge.config.json");
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
throw new ToolRefusal("config-invalid", "the trusted comforge.config.json is invalid", 2, {
|
|
65
|
+
repository: binding.id,
|
|
66
|
+
reason: error instanceof Error ? error.message.slice(0, 500) : "invalid",
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const base = `refs/remotes/${config.repository.remote}/${config.repository.baseBranch}`;
|
|
70
|
+
const atBase = read(base);
|
|
71
|
+
if (atBase.status === 0 && atBase.stdout !== r.stdout)
|
|
72
|
+
config = parseConfig(atBase.stdout, "comforge.config.json");
|
|
73
|
+
if (config.repository.owner !== binding.owner || config.repository.name !== binding.name)
|
|
74
|
+
throw new ToolRefusal("repository-mismatch", "the trusted configuration names another repository", 1, {
|
|
75
|
+
repository: binding.id,
|
|
76
|
+
});
|
|
77
|
+
return config;
|
|
78
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type Principal } from "./contracts.ts";
|
|
2
|
+
import type { HostServices, IsolationProvider, RepositoryBinding } from "./host.ts";
|
|
3
|
+
export interface HttpLimits {
|
|
4
|
+
maxBodyBytes: number;
|
|
5
|
+
maxSessions: number;
|
|
6
|
+
sessionIdleMs: number;
|
|
7
|
+
requestsPerMinute: number;
|
|
8
|
+
maxConcurrentPerPrincipal: number;
|
|
9
|
+
}
|
|
10
|
+
export declare const DEFAULT_HTTP_LIMITS: HttpLimits;
|
|
11
|
+
export interface HttpOptions {
|
|
12
|
+
repositories: readonly RepositoryBinding[];
|
|
13
|
+
host: HostServices;
|
|
14
|
+
/** The host's authentication: a principal for this request, or null for 401. */
|
|
15
|
+
authenticate(request: Request): Promise<Principal | null> | Principal | null;
|
|
16
|
+
/** Exact `Host` header values served; required, never empty. */
|
|
17
|
+
allowedHosts: readonly string[];
|
|
18
|
+
/** Exact `Origin` values accepted when a request carries one (browsers do). */
|
|
19
|
+
allowedOrigins: readonly string[];
|
|
20
|
+
/** `WWW-Authenticate` value for 401 answers (e.g. a Bearer challenge with resource metadata). */
|
|
21
|
+
challenge?: string;
|
|
22
|
+
isolation?: IsolationProvider;
|
|
23
|
+
/** See ComforgeMcpOptions.compactDiscovery. */
|
|
24
|
+
compactDiscovery?: boolean;
|
|
25
|
+
/** See ComforgeMcpOptions.textContent. */
|
|
26
|
+
textContent?: "full" | "summary";
|
|
27
|
+
limits?: Partial<HttpLimits>;
|
|
28
|
+
now?: () => number;
|
|
29
|
+
}
|
|
30
|
+
export declare const fingerprintOf: (p: Principal) => string;
|
|
31
|
+
export interface HttpHandler {
|
|
32
|
+
handle(request: Request): Promise<Response>;
|
|
33
|
+
/** Live sessions (for tests and health reporting). */
|
|
34
|
+
sessions(): number;
|
|
35
|
+
close(): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
export declare function createHttpHandler(options: HttpOptions): HttpHandler;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streamable HTTP for comforge-mcp, as a web-standard `(Request) => Promise<Response>`
|
|
3
|
+
* handler the host mounts in its own HTTP server (Node, Bun, Deno, a framework route).
|
|
4
|
+
*
|
|
5
|
+
* Order of checks, before any MCP message is parsed:
|
|
6
|
+
* Host allowlist (DNS rebinding) → Origin allowlist → method → body size →
|
|
7
|
+
* host authentication (a principal or 401) → per-principal rate and concurrency →
|
|
8
|
+
* session: created by `initialize` and bound to that principal; any other principal
|
|
9
|
+
* presenting its id is refused, an unknown or expired id is 404.
|
|
10
|
+
*
|
|
11
|
+
* Authentication is the host's: this module never sees a password, cookie or token format,
|
|
12
|
+
* only the principal `authenticate` returns. Executing tools exist on this transport only
|
|
13
|
+
* with a host `IsolationProvider` (see host.ts).
|
|
14
|
+
*/
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
17
|
+
import { PrincipalSchema } from "./contracts.js";
|
|
18
|
+
import { assertIsolation, createComforgeMcpServer } from "./server.js";
|
|
19
|
+
export const DEFAULT_HTTP_LIMITS = {
|
|
20
|
+
maxBodyBytes: 1_000_000,
|
|
21
|
+
maxSessions: 32,
|
|
22
|
+
sessionIdleMs: 15 * 60_000,
|
|
23
|
+
requestsPerMinute: 60,
|
|
24
|
+
maxConcurrentPerPrincipal: 4,
|
|
25
|
+
};
|
|
26
|
+
const json = (status, message, headers = {}) => new Response(JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message }, id: null }), {
|
|
27
|
+
status,
|
|
28
|
+
headers: { "content-type": "application/json", ...headers },
|
|
29
|
+
});
|
|
30
|
+
export const fingerprintOf = (p) => JSON.stringify([
|
|
31
|
+
p.id,
|
|
32
|
+
[...p.profiles].sort(),
|
|
33
|
+
p.repositories === "*" ? "*" : [...p.repositories].sort(),
|
|
34
|
+
]);
|
|
35
|
+
export function createHttpHandler(options) {
|
|
36
|
+
if (options.allowedHosts.length === 0)
|
|
37
|
+
throw new Error("allowedHosts must name the served host");
|
|
38
|
+
if (options.isolation)
|
|
39
|
+
assertIsolation(options.isolation);
|
|
40
|
+
const limits = { ...DEFAULT_HTTP_LIMITS, ...options.limits };
|
|
41
|
+
const now = options.now ?? Date.now;
|
|
42
|
+
const sessions = new Map();
|
|
43
|
+
const windows = new Map();
|
|
44
|
+
const inflight = new Map();
|
|
45
|
+
const sweep = () => {
|
|
46
|
+
for (const [id, s] of sessions)
|
|
47
|
+
if (now() - s.lastUsed > limits.sessionIdleMs) {
|
|
48
|
+
sessions.delete(id);
|
|
49
|
+
void s.transport.close();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const rateLimited = (principalId) => {
|
|
53
|
+
const w = windows.get(principalId);
|
|
54
|
+
if (!w || now() - w.start >= 60_000) {
|
|
55
|
+
windows.set(principalId, { start: now(), count: 1 });
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
w.count += 1;
|
|
59
|
+
return w.count > limits.requestsPerMinute;
|
|
60
|
+
};
|
|
61
|
+
async function handle(request) {
|
|
62
|
+
const host = request.headers.get("host");
|
|
63
|
+
if (!host || !options.allowedHosts.includes(host))
|
|
64
|
+
return json(421, "host not served");
|
|
65
|
+
const origin = request.headers.get("origin");
|
|
66
|
+
if (origin !== null && !options.allowedOrigins.includes(origin))
|
|
67
|
+
return json(403, "origin not allowed");
|
|
68
|
+
if (!["POST", "GET", "DELETE"].includes(request.method))
|
|
69
|
+
return json(405, "method not allowed", { allow: "POST, GET, DELETE" });
|
|
70
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
71
|
+
if (Number.isFinite(declared) && declared > limits.maxBodyBytes)
|
|
72
|
+
return json(413, "request too large");
|
|
73
|
+
// An authenticator that throws is an ambiguous identity: refused, never guessed.
|
|
74
|
+
let raw;
|
|
75
|
+
try {
|
|
76
|
+
raw = await options.authenticate(request);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
raw = null;
|
|
80
|
+
}
|
|
81
|
+
const parsed = raw ? PrincipalSchema.safeParse(raw) : null;
|
|
82
|
+
if (!parsed?.success)
|
|
83
|
+
return json(401, "authentication required", options.challenge ? { "www-authenticate": options.challenge } : {});
|
|
84
|
+
const principal = parsed.data;
|
|
85
|
+
if (rateLimited(principal.id))
|
|
86
|
+
return json(429, "rate limit", { "retry-after": "60" });
|
|
87
|
+
if ((inflight.get(principal.id) ?? 0) >= limits.maxConcurrentPerPrincipal)
|
|
88
|
+
return json(429, "too many concurrent requests", { "retry-after": "1" });
|
|
89
|
+
sweep();
|
|
90
|
+
inflight.set(principal.id, (inflight.get(principal.id) ?? 0) + 1);
|
|
91
|
+
try {
|
|
92
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
93
|
+
if (sessionId) {
|
|
94
|
+
const session = sessions.get(sessionId);
|
|
95
|
+
if (!session)
|
|
96
|
+
return json(404, "unknown or expired session");
|
|
97
|
+
// Session binding: the id alone never authorizes; it must be presented by its principal.
|
|
98
|
+
if (session.principalId !== principal.id)
|
|
99
|
+
return json(403, "session belongs to another principal");
|
|
100
|
+
// A changed or revoked role ends the session: its tools were registered for the old one.
|
|
101
|
+
if (session.fingerprint !== fingerprintOf(principal)) {
|
|
102
|
+
sessions.delete(sessionId);
|
|
103
|
+
void session.transport.close();
|
|
104
|
+
return json(403, "the principal's profiles or repositories changed; start a new session");
|
|
105
|
+
}
|
|
106
|
+
session.lastUsed = now();
|
|
107
|
+
const response = await session.transport.handleRequest(request);
|
|
108
|
+
if (request.method === "DELETE")
|
|
109
|
+
sessions.delete(sessionId);
|
|
110
|
+
return response;
|
|
111
|
+
}
|
|
112
|
+
if (request.method !== "POST")
|
|
113
|
+
return json(400, "a session id is required");
|
|
114
|
+
// A new session starts only with `initialize`; the transport refuses anything else.
|
|
115
|
+
if (sessions.size >= limits.maxSessions)
|
|
116
|
+
return json(503, "session limit reached", { "retry-after": "60" });
|
|
117
|
+
let created = null;
|
|
118
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
119
|
+
sessionIdGenerator: () => randomUUID(),
|
|
120
|
+
enableJsonResponse: true,
|
|
121
|
+
maxRequestBodySize: limits.maxBodyBytes,
|
|
122
|
+
onsessioninitialized: (id) => {
|
|
123
|
+
created = id;
|
|
124
|
+
sessions.set(id, {
|
|
125
|
+
transport,
|
|
126
|
+
principalId: principal.id,
|
|
127
|
+
fingerprint: fingerprintOf(principal),
|
|
128
|
+
lastUsed: now(),
|
|
129
|
+
});
|
|
130
|
+
},
|
|
131
|
+
onsessionclosed: (id) => {
|
|
132
|
+
sessions.delete(id);
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
const server = createComforgeMcpServer({
|
|
136
|
+
repositories: options.repositories,
|
|
137
|
+
host: options.host,
|
|
138
|
+
principal,
|
|
139
|
+
transport: "http",
|
|
140
|
+
...(options.isolation ? { isolation: options.isolation } : {}),
|
|
141
|
+
...(options.compactDiscovery ? { compactDiscovery: true } : {}),
|
|
142
|
+
...(options.textContent ? { textContent: options.textContent } : {}),
|
|
143
|
+
});
|
|
144
|
+
await server.connect(transport);
|
|
145
|
+
const response = await transport.handleRequest(request);
|
|
146
|
+
if (!created)
|
|
147
|
+
await transport.close();
|
|
148
|
+
return response;
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
inflight.set(principal.id, (inflight.get(principal.id) ?? 1) - 1);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
handle,
|
|
156
|
+
sessions: () => sessions.size,
|
|
157
|
+
async close() {
|
|
158
|
+
for (const s of sessions.values())
|
|
159
|
+
await s.transport.close();
|
|
160
|
+
sessions.clear();
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @comforge/mcp: the @comforge/cli lifecycle as an MCP server, for local stdio and
|
|
3
|
+
* Streamable HTTP. Embed it with `createComforgeMcpServer`, `serveStdio` or
|
|
4
|
+
* `createHttpHandler`; run it locally with the `comforge-mcp` executable.
|
|
5
|
+
*/
|
|
6
|
+
export { CAPABILITIES_SCHEMA, ERROR_SCHEMA, GrantEnvelope, INPUTS, LIMITS, PROFILES, type Principal, PrincipalSchema, type Profile, RESULT_SCHEMA, TOOL_NAMES, TOOLS, type ToolContract, type ToolName, } from "./contracts.ts";
|
|
7
|
+
export { type AuditEvent, assertBindings, type HostServices, type IsolationProvider, type RepositoryBinding, trustedConfig, } from "./host.ts";
|
|
8
|
+
export { createHttpHandler, DEFAULT_HTTP_LIMITS, type HttpHandler, type HttpLimits, type HttpOptions, } from "./http.ts";
|
|
9
|
+
export { MCP_CODES, type McpError, type ToolSuccess } from "./results.ts";
|
|
10
|
+
export { type ComforgeMcpOptions, createComforgeMcpServer, discoverableTools, permitted, } from "./server.ts";
|
|
11
|
+
export { type StdioOptions, serveStdio } from "./stdio.ts";
|
|
12
|
+
export { SERVER_NAME, SERVER_VERSION } from "./tools.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @comforge/mcp: the @comforge/cli lifecycle as an MCP server, for local stdio and
|
|
3
|
+
* Streamable HTTP. Embed it with `createComforgeMcpServer`, `serveStdio` or
|
|
4
|
+
* `createHttpHandler`; run it locally with the `comforge-mcp` executable.
|
|
5
|
+
*/
|
|
6
|
+
export { CAPABILITIES_SCHEMA, ERROR_SCHEMA, GrantEnvelope, INPUTS, LIMITS, PROFILES, PrincipalSchema, RESULT_SCHEMA, TOOL_NAMES, TOOLS, } from "./contracts.js";
|
|
7
|
+
export { assertBindings, trustedConfig, } from "./host.js";
|
|
8
|
+
export { createHttpHandler, DEFAULT_HTTP_LIMITS, } from "./http.js";
|
|
9
|
+
export { MCP_CODES } from "./results.js";
|
|
10
|
+
export { createComforgeMcpServer, discoverableTools, permitted, } from "./server.js";
|
|
11
|
+
export { serveStdio } from "./stdio.js";
|
|
12
|
+
export { SERVER_NAME, SERVER_VERSION } from "./tools.js";
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result shaping: summary first, bounded, paginated, redacted.
|
|
3
|
+
*
|
|
4
|
+
* A tool result is `{schema, tool, ok, summary, data, page?}`; a refusal is a structured
|
|
5
|
+
* error `{schema, code, message, exit, retryable, hint?, detail?}` returned with `isError`.
|
|
6
|
+
* Nothing here decides governance: codes and exit classes are @comforge/cli's own.
|
|
7
|
+
*/
|
|
8
|
+
import { type ServiceError } from "@comforge/cli";
|
|
9
|
+
import { ERROR_SCHEMA, RESULT_SCHEMA, type ToolName } from "./contracts.ts";
|
|
10
|
+
export interface McpError {
|
|
11
|
+
schema: typeof ERROR_SCHEMA;
|
|
12
|
+
code: string;
|
|
13
|
+
message: string;
|
|
14
|
+
/** @comforge/cli exit class: 1 refused, 2 usage, 3 failed, 4 incomplete. */
|
|
15
|
+
exit: number;
|
|
16
|
+
retryable: boolean;
|
|
17
|
+
hint?: string;
|
|
18
|
+
detail?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
export declare class ToolRefusal extends Error {
|
|
21
|
+
readonly code: string;
|
|
22
|
+
readonly exit: number;
|
|
23
|
+
readonly detail: Record<string, unknown>;
|
|
24
|
+
readonly hint: string | undefined;
|
|
25
|
+
constructor(code: string, message: string, exit?: number, detail?: Record<string, unknown>, hint?: string);
|
|
26
|
+
}
|
|
27
|
+
/** Codes this server adds; every other code is @comforge/cli's. */
|
|
28
|
+
export declare const MCP_CODES: {
|
|
29
|
+
readonly "unknown-repository": "the repository id is not allowlisted for this principal";
|
|
30
|
+
readonly "repository-mismatch": "the repository's trusted configuration names another repository";
|
|
31
|
+
readonly "profile-denied": "the principal's profiles do not include this tool";
|
|
32
|
+
readonly "execution-unavailable": "this transport has no host-provided isolation for repository commands";
|
|
33
|
+
readonly "command-scope-unsupported": "the published grant format cannot scope a grant to this command";
|
|
34
|
+
readonly "result-too-large": "the request would return more than the result bound";
|
|
35
|
+
readonly unavailable: "the published dependency does not provide this read";
|
|
36
|
+
};
|
|
37
|
+
/** Replaces every value a caller must never see: the call's credentials and secret-like text. */
|
|
38
|
+
export declare function redact(value: unknown, secrets: readonly string[]): unknown;
|
|
39
|
+
export declare function fromServiceError(error: ServiceError): McpError;
|
|
40
|
+
export declare function fromRefusal(r: ToolRefusal): McpError;
|
|
41
|
+
export declare function internalError(): McpError;
|
|
42
|
+
/** Truncates long strings and caps the serialized size of a value. */
|
|
43
|
+
export declare function bound(value: unknown, maxChars?: number): unknown;
|
|
44
|
+
export declare function excerpt(text: string, detail: boolean): {
|
|
45
|
+
text: string;
|
|
46
|
+
truncated: boolean;
|
|
47
|
+
};
|
|
48
|
+
export interface Page<T> {
|
|
49
|
+
items: T[];
|
|
50
|
+
page: {
|
|
51
|
+
cursor: string;
|
|
52
|
+
next: string | null;
|
|
53
|
+
total: number;
|
|
54
|
+
pageSize: number;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export declare function paginate<T>(all: readonly T[], cursor?: string, pageSize?: number): Page<T>;
|
|
58
|
+
export interface ToolSuccess {
|
|
59
|
+
schema: typeof RESULT_SCHEMA;
|
|
60
|
+
tool: ToolName;
|
|
61
|
+
ok: true;
|
|
62
|
+
/** @comforge/cli exit class of the result: 0, or 1 for a recorded FAIL (verify). */
|
|
63
|
+
exit: number;
|
|
64
|
+
summary: string;
|
|
65
|
+
data: Record<string, unknown>;
|
|
66
|
+
page?: Page<unknown>["page"];
|
|
67
|
+
}
|
|
68
|
+
export declare function success(tool: ToolName, summary: string, data: Record<string, unknown>, page?: Page<unknown>["page"], exit?: number): ToolSuccess;
|
|
69
|
+
/** A delivery the CLI recorded as incomplete: its code, at the stage that failed. */
|
|
70
|
+
export declare function incompleteDelivery(v: {
|
|
71
|
+
delivery: string;
|
|
72
|
+
attempt?: number;
|
|
73
|
+
failedStage?: string;
|
|
74
|
+
stages: Record<string, unknown>;
|
|
75
|
+
error?: {
|
|
76
|
+
code?: string;
|
|
77
|
+
message: string;
|
|
78
|
+
detail?: unknown;
|
|
79
|
+
};
|
|
80
|
+
}, exit: number): McpError;
|
package/dist/results.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result shaping: summary first, bounded, paginated, redacted.
|
|
3
|
+
*
|
|
4
|
+
* A tool result is `{schema, tool, ok, summary, data, page?}`; a refusal is a structured
|
|
5
|
+
* error `{schema, code, message, exit, retryable, hint?, detail?}` returned with `isError`.
|
|
6
|
+
* Nothing here decides governance: codes and exit classes are @comforge/cli's own.
|
|
7
|
+
*/
|
|
8
|
+
import { detectSecrets } from "@comforge/cli";
|
|
9
|
+
import { ERROR_SCHEMA, LIMITS, RESULT_SCHEMA } from "./contracts.js";
|
|
10
|
+
export class ToolRefusal extends Error {
|
|
11
|
+
code;
|
|
12
|
+
exit;
|
|
13
|
+
detail;
|
|
14
|
+
hint;
|
|
15
|
+
constructor(code, message, exit = 1, detail = {}, hint) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.exit = exit;
|
|
19
|
+
this.detail = detail;
|
|
20
|
+
this.hint = hint;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Codes this server adds; every other code is @comforge/cli's. */
|
|
24
|
+
export const MCP_CODES = {
|
|
25
|
+
"unknown-repository": "the repository id is not allowlisted for this principal",
|
|
26
|
+
"repository-mismatch": "the repository's trusted configuration names another repository",
|
|
27
|
+
"profile-denied": "the principal's profiles do not include this tool",
|
|
28
|
+
"execution-unavailable": "this transport has no host-provided isolation for repository commands",
|
|
29
|
+
"command-scope-unsupported": "the published grant format cannot scope a grant to this command",
|
|
30
|
+
"result-too-large": "the request would return more than the result bound",
|
|
31
|
+
unavailable: "the published dependency does not provide this read",
|
|
32
|
+
};
|
|
33
|
+
const HINTS = {
|
|
34
|
+
"authorization-required": "the trusted configuration has no security.authorization; that is an owner decision",
|
|
35
|
+
unauthorized: "a write needs a valid owner grant for this initiative and head (operator mode needs none)",
|
|
36
|
+
"credential-missing": "the server has no credential for this repository; credentials are server-owned",
|
|
37
|
+
"validation-missing": "run comforge_verify on this exact commit first",
|
|
38
|
+
stale: "re-read the pull request or initiative; the head moved",
|
|
39
|
+
"untrusted-config-change": "configuration changes take effect only from the trusted base branch",
|
|
40
|
+
incomplete: "call comforge_recover, then retry",
|
|
41
|
+
ambiguous: "call comforge_recover; an earlier write may have been applied",
|
|
42
|
+
cancelled: "the call stopped between stages; comforge_status shows where",
|
|
43
|
+
"execution-unavailable": "use a local stdio server, or a host that provides isolation",
|
|
44
|
+
"command-scope-unsupported": "run cleanup through the comforge CLI as the owner",
|
|
45
|
+
"unknown-repository": "comforge_capabilities lists the repositories you may use",
|
|
46
|
+
};
|
|
47
|
+
/** Retrying the same call can help only for transient failures, never for a refusal. */
|
|
48
|
+
const RETRYABLE = new Set(["git-failed", "github-failed", "io", "ledger"]);
|
|
49
|
+
/** Replaces every value a caller must never see: the call's credentials and secret-like text. */
|
|
50
|
+
export function redact(value, secrets) {
|
|
51
|
+
const known = secrets.filter((s) => s.length >= 8);
|
|
52
|
+
const visit = (v, depth) => {
|
|
53
|
+
if (depth > 12)
|
|
54
|
+
return "[depth limit]";
|
|
55
|
+
if (typeof v === "string") {
|
|
56
|
+
let out = v;
|
|
57
|
+
for (const s of known)
|
|
58
|
+
out = out.split(s).join("[redacted]");
|
|
59
|
+
return detectSecrets(out).count > 0 ? "[redacted: secret-like text]" : out;
|
|
60
|
+
}
|
|
61
|
+
if (Array.isArray(v))
|
|
62
|
+
return v.map((x) => visit(x, depth + 1));
|
|
63
|
+
if (v && typeof v === "object")
|
|
64
|
+
return Object.fromEntries(Object.entries(v)
|
|
65
|
+
.filter(([k]) => !/token|secret|password|passphrase|privatekey/i.test(k))
|
|
66
|
+
.map(([k, x]) => [k, visit(x, depth + 1)]));
|
|
67
|
+
return v;
|
|
68
|
+
};
|
|
69
|
+
return visit(value, 0);
|
|
70
|
+
}
|
|
71
|
+
export function fromServiceError(error) {
|
|
72
|
+
return {
|
|
73
|
+
schema: ERROR_SCHEMA,
|
|
74
|
+
code: error.code,
|
|
75
|
+
message: error.message,
|
|
76
|
+
exit: error.exit,
|
|
77
|
+
retryable: RETRYABLE.has(error.code),
|
|
78
|
+
...(HINTS[error.code] ? { hint: HINTS[error.code] } : {}),
|
|
79
|
+
...(Object.keys(error.detail ?? {}).length > 0
|
|
80
|
+
? { detail: bound(error.detail, 4_000) }
|
|
81
|
+
: {}),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export function fromRefusal(r) {
|
|
85
|
+
return {
|
|
86
|
+
schema: ERROR_SCHEMA,
|
|
87
|
+
code: r.code,
|
|
88
|
+
message: r.message,
|
|
89
|
+
exit: r.exit,
|
|
90
|
+
retryable: false,
|
|
91
|
+
...((r.hint ?? HINTS[r.code]) ? { hint: r.hint ?? HINTS[r.code] } : {}),
|
|
92
|
+
...(Object.keys(r.detail).length > 0 ? { detail: r.detail } : {}),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export function internalError() {
|
|
96
|
+
return {
|
|
97
|
+
schema: ERROR_SCHEMA,
|
|
98
|
+
code: "internal",
|
|
99
|
+
message: "the server failed unexpectedly; nothing about the failure is returned",
|
|
100
|
+
exit: 3,
|
|
101
|
+
retryable: false,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** Truncates long strings and caps the serialized size of a value. */
|
|
105
|
+
export function bound(value, maxChars = LIMITS.maxResultChars) {
|
|
106
|
+
const clip = (v, depth) => {
|
|
107
|
+
if (typeof v === "string")
|
|
108
|
+
return v.length > LIMITS.detailChars ? `${v.slice(0, LIMITS.detailChars)}… [truncated]` : v;
|
|
109
|
+
if (depth > 12)
|
|
110
|
+
return "[depth limit]";
|
|
111
|
+
if (Array.isArray(v))
|
|
112
|
+
return v.map((x) => clip(x, depth + 1));
|
|
113
|
+
if (v && typeof v === "object")
|
|
114
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, clip(x, depth + 1)]));
|
|
115
|
+
return v;
|
|
116
|
+
};
|
|
117
|
+
const clipped = clip(value, 0);
|
|
118
|
+
const text = JSON.stringify(clipped) ?? "null";
|
|
119
|
+
if (text.length <= maxChars)
|
|
120
|
+
return clipped;
|
|
121
|
+
return {
|
|
122
|
+
truncated: true,
|
|
123
|
+
chars: text.length,
|
|
124
|
+
excerpt: `${text.slice(0, Math.max(0, maxChars - 200))}…`,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
export function excerpt(text, detail) {
|
|
128
|
+
const max = detail ? LIMITS.detailChars : LIMITS.excerptChars;
|
|
129
|
+
return text.length > max
|
|
130
|
+
? { text: text.slice(0, max), truncated: true }
|
|
131
|
+
: { text, truncated: false };
|
|
132
|
+
}
|
|
133
|
+
export function paginate(all, cursor, pageSize) {
|
|
134
|
+
const size = Math.min(pageSize ?? LIMITS.pageSize, LIMITS.maxPageSize);
|
|
135
|
+
const start = cursor ? Number(cursor) : 0;
|
|
136
|
+
const items = all.slice(start, start + size);
|
|
137
|
+
const nextAt = start + items.length;
|
|
138
|
+
return {
|
|
139
|
+
items,
|
|
140
|
+
page: {
|
|
141
|
+
cursor: String(start),
|
|
142
|
+
next: nextAt < all.length ? String(nextAt) : null,
|
|
143
|
+
total: all.length,
|
|
144
|
+
pageSize: size,
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
export function success(tool, summary, data, page, exit = 0) {
|
|
149
|
+
return { schema: RESULT_SCHEMA, tool, ok: true, exit, summary, data, ...(page ? { page } : {}) };
|
|
150
|
+
}
|
|
151
|
+
/** A delivery the CLI recorded as incomplete: its code, at the stage that failed. */
|
|
152
|
+
export function incompleteDelivery(v, exit) {
|
|
153
|
+
const code = v.error?.code ?? "incomplete";
|
|
154
|
+
return {
|
|
155
|
+
schema: ERROR_SCHEMA,
|
|
156
|
+
code,
|
|
157
|
+
message: v.error?.message ?? "the delivery is incomplete",
|
|
158
|
+
exit,
|
|
159
|
+
retryable: RETRYABLE.has(code),
|
|
160
|
+
...(HINTS[code] ? { hint: HINTS[code] } : {}),
|
|
161
|
+
detail: bound({
|
|
162
|
+
delivery: v.delivery,
|
|
163
|
+
attempt: v.attempt ?? null,
|
|
164
|
+
failedStage: v.failedStage ?? null,
|
|
165
|
+
stages: v.stages,
|
|
166
|
+
cause: v.error?.detail ?? null,
|
|
167
|
+
}, 6_000),
|
|
168
|
+
};
|
|
169
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { type Principal, type ToolName } from "./contracts.ts";
|
|
3
|
+
import { type HostServices, type IsolationProvider, type RepositoryBinding } from "./host.ts";
|
|
4
|
+
export interface ComforgeMcpOptions {
|
|
5
|
+
repositories: readonly RepositoryBinding[];
|
|
6
|
+
host: HostServices;
|
|
7
|
+
principal: Principal;
|
|
8
|
+
transport: "stdio" | "http";
|
|
9
|
+
/** Required for executing tools over HTTP. Ignored on stdio, where the local user runs them. */
|
|
10
|
+
isolation?: IsolationProvider;
|
|
11
|
+
/**
|
|
12
|
+
* Leave the per-tool output schemas out of discovery. Results keep the same versioned
|
|
13
|
+
* envelope (`schema: "comforge-mcp/v1"`, documented and exported as RESULT_SCHEMA); a
|
|
14
|
+
* client that validates structured output should leave this off.
|
|
15
|
+
*/
|
|
16
|
+
compactDiscovery?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* What a successful result's text content carries. "full" (default): the result JSON, for
|
|
19
|
+
* clients that read only text. "summary": the one-line summary and a pointer to the
|
|
20
|
+
* structured content, so a client that gives the model structuredContent does not pay for
|
|
21
|
+
* the same result twice. Errors always carry their full JSON (they have no structured content).
|
|
22
|
+
*/
|
|
23
|
+
textContent?: "full" | "summary";
|
|
24
|
+
}
|
|
25
|
+
export declare function permitted(principal: Principal, tool: ToolName): boolean;
|
|
26
|
+
/** The tools a principal discovers on a transport. */
|
|
27
|
+
export declare function discoverableTools(principal: Principal, transport: "stdio" | "http", isolation?: IsolationProvider): ToolName[];
|
|
28
|
+
/** A provider is code the host wires in; anything else is a configuration error. */
|
|
29
|
+
export declare function assertIsolation(isolation: IsolationProvider): void;
|
|
30
|
+
export declare function createComforgeMcpServer(options: ComforgeMcpOptions): McpServer;
|