@comforge/mcp 0.0.0-stage → 0.2.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/dist/host.d.ts ADDED
@@ -0,0 +1,104 @@
1
+ import { type ComforgeConfig, type CredentialProvider, type HostPolicy, type Runtime, type StateStore } from "@comforge/cli";
2
+ import type { Principal } from "./contracts.ts";
3
+ export interface RepositoryBinding {
4
+ /** Allowlisted id callers use. */
5
+ id: string;
6
+ /** Absolute path of the primary checkout. Never shown to, or taken from, a caller. */
7
+ root: string;
8
+ /** Git common directory; defaults to `<root>/.git`. */
9
+ commonDir?: string;
10
+ /** GitHub identity the trusted configuration must name. */
11
+ owner: string;
12
+ name: string;
13
+ }
14
+ /**
15
+ * Host-provided isolation for repository commands over a remote transport. The host
16
+ * attests that `runtime` runs every command inside an isolation boundary it operates
17
+ * (container, VM, dedicated worker). A flag cannot stand in for it: without a provider,
18
+ * executing tools are neither listed nor callable over HTTP.
19
+ */
20
+ export interface IsolationProvider {
21
+ /** Non-secret identifier of the isolation, recorded in audit events and capabilities. */
22
+ readonly id: string;
23
+ runtime(binding: RepositoryBinding, principal: Principal): Runtime;
24
+ }
25
+ export interface AuditEvent {
26
+ tool: string;
27
+ principal: string;
28
+ repository: string | null;
29
+ outcome: "ok" | "refused" | "error";
30
+ code: string | null;
31
+ durationMs: number;
32
+ transport: "stdio" | "http";
33
+ }
34
+ export interface HostServices {
35
+ /** The runtime for read-only work and, on stdio, for repository commands. */
36
+ runtime(binding: RepositoryBinding): Runtime;
37
+ /** Server-owned credentials; never returned to a caller. Omit to use the configuration's source. */
38
+ credentials?(binding: RepositoryBinding, principal: Principal): CredentialProvider | undefined;
39
+ /** Shared initiative store; omit for the CLI's default, so the CLI and the server agree. */
40
+ state?(binding: RepositoryBinding): StateStore | undefined;
41
+ /** Called once per tool call, with no arguments, bodies or credentials. */
42
+ audit?(event: AuditEvent): void;
43
+ /**
44
+ * Trusted host policy for the lifecycle (checkout parent, worker preparation and removal,
45
+ * validation), per repository. Host code only: no tool input reaches it.
46
+ */
47
+ hostPolicy?(binding: RepositoryBinding): HostPolicy | undefined;
48
+ }
49
+ /** Refuses an allowlist with duplicate or malformed ids, or relative paths. */
50
+ export declare function assertBindings(bindings: readonly RepositoryBinding[]): void;
51
+ export declare function resolveBinding(bindings: readonly RepositoryBinding[], principal: Principal, id: string): RepositoryBinding;
52
+ export declare const repositoryOf: (b: RepositoryBinding) => {
53
+ root: string;
54
+ commonDir: string;
55
+ };
56
+ /**
57
+ * The configuration at the base branch's remote-tracking ref: what @comforge/cli trusts.
58
+ * The working tree's copy is ignored. It must name the binding's repository.
59
+ */
60
+ export declare function trustedConfig(rt: Runtime, binding: RepositoryBinding): ComforgeConfig;
61
+ /**
62
+ * An allowlisted repository the host serves without a local checkout: GitHub evidence reads
63
+ * only (issue, pull request, pull requests, comments, advisory reviews, artifacts). Lifecycle,
64
+ * state and executing tools are refused for it (`checkout-required`): they need a checkout and,
65
+ * remotely, isolation, which loading a configuration never provides.
66
+ */
67
+ export interface RemoteRepositoryBinding {
68
+ id: string;
69
+ owner: string;
70
+ name: string;
71
+ /**
72
+ * sha256 (hex) of the trusted `comforge.config.json` bytes the host pins. When set, any other
73
+ * configuration is refused (`config-mismatch`), even one committed at the base.
74
+ */
75
+ configSha256?: string;
76
+ }
77
+ /** The trusted configuration as the host observed it: bytes at one immutable base revision. */
78
+ export interface TrustedConfigSnapshot {
79
+ /** Full 40-hex commit of the base branch the host trusts. */
80
+ revision: string;
81
+ /** The exact `comforge.config.json` text at `revision`. */
82
+ text: string;
83
+ /** When the host observed `revision` as the base head (ms since epoch). */
84
+ observedAt: number;
85
+ }
86
+ /**
87
+ * Host code for checkout-free repositories. The server never takes a configuration, revision,
88
+ * URL or credential from a caller: the host supplies them, and the server checks the snapshot
89
+ * against GitHub (the same bytes at that revision), its pin, its age and its repository.
90
+ */
91
+ export interface RemoteHost {
92
+ trustedConfig(binding: RemoteRepositoryBinding): TrustedConfigSnapshot | Promise<TrustedConfigSnapshot>;
93
+ /** Server-owned GitHub token for the binding; never returned to a caller. */
94
+ credentials(binding: RemoteRepositoryBinding, principal: Principal): string | undefined;
95
+ /** Oldest snapshot accepted; default 10 minutes. */
96
+ configMaxAgeMs?: number;
97
+ fetchImpl?: typeof fetch;
98
+ now?(): number;
99
+ }
100
+ /** Refuses malformed remote bindings, and an id used by a local and a remote binding alike. */
101
+ export declare function assertRemoteBindings(remote: readonly RemoteRepositoryBinding[], local: readonly RepositoryBinding[]): void;
102
+ export declare function resolveRemoteBinding(remote: readonly RemoteRepositoryBinding[], principal: Principal, id: string): RemoteRepositoryBinding | null;
103
+ /** The snapshot's own checks: revision shape, age, pin, parse and repository identity. */
104
+ export declare function checkSnapshot(binding: RemoteRepositoryBinding, snapshot: TrustedConfigSnapshot, now: number, maxAgeMs: number): ComforgeConfig;
package/dist/host.js ADDED
@@ -0,0 +1,132 @@
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 { createHash } from "node:crypto";
10
+ import { parseConfig, } from "@comforge/cli";
11
+ import { ToolRefusal } from "./results.js";
12
+ const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
13
+ /** Refuses an allowlist with duplicate or malformed ids, or relative paths. */
14
+ export function assertBindings(bindings) {
15
+ const seen = new Set();
16
+ for (const b of bindings) {
17
+ if (!ID.test(b.id))
18
+ throw new Error(`repository id ${JSON.stringify(b.id)} is malformed`);
19
+ if (seen.has(b.id))
20
+ throw new Error(`repository id ${b.id} is listed twice`);
21
+ seen.add(b.id);
22
+ if (!b.root.startsWith("/"))
23
+ throw new Error(`repository ${b.id}: root must be absolute`);
24
+ if (b.commonDir && !b.commonDir.startsWith("/"))
25
+ throw new Error(`repository ${b.id}: commonDir must be absolute`);
26
+ }
27
+ }
28
+ export function resolveBinding(bindings, principal, id) {
29
+ const binding = bindings.find((b) => b.id === id);
30
+ const allowed = principal.repositories === "*" || principal.repositories.includes(id);
31
+ // The same refusal whether the id is unknown or not the principal's: no allowlist probing.
32
+ if (!binding || !allowed)
33
+ throw new ToolRefusal("unknown-repository", `no repository ${id} for this principal`, 1, {
34
+ repository: id,
35
+ });
36
+ return binding;
37
+ }
38
+ export const repositoryOf = (b) => ({
39
+ root: b.root,
40
+ commonDir: b.commonDir ?? `${b.root}/.git`,
41
+ });
42
+ /**
43
+ * The configuration at the base branch's remote-tracking ref: what @comforge/cli trusts.
44
+ * The working tree's copy is ignored. It must name the binding's repository.
45
+ */
46
+ export function trustedConfig(rt, binding) {
47
+ const read = (ref) => rt.run("git", ["show", `${ref}:comforge.config.json`], {
48
+ cwd: binding.root,
49
+ timeoutMs: 15_000,
50
+ });
51
+ // The base branch comes from the committed configuration itself, read at origin's HEAD
52
+ // first; a repository without one is refused like the CLI refuses it.
53
+ let r = read("refs/remotes/origin/HEAD");
54
+ if (r.status !== 0)
55
+ r = read("refs/remotes/origin/main");
56
+ if (r.status !== 0)
57
+ throw new ToolRefusal("config-missing", "the repository has no trusted comforge.config.json", 2, {
58
+ repository: binding.id,
59
+ });
60
+ let config;
61
+ try {
62
+ config = parseConfig(r.stdout, "comforge.config.json");
63
+ }
64
+ catch (error) {
65
+ throw new ToolRefusal("config-invalid", "the trusted comforge.config.json is invalid", 2, {
66
+ repository: binding.id,
67
+ reason: error instanceof Error ? error.message.slice(0, 500) : "invalid",
68
+ });
69
+ }
70
+ const base = `refs/remotes/${config.repository.remote}/${config.repository.baseBranch}`;
71
+ const atBase = read(base);
72
+ if (atBase.status === 0 && atBase.stdout !== r.stdout)
73
+ config = parseConfig(atBase.stdout, "comforge.config.json");
74
+ if (config.repository.owner !== binding.owner || config.repository.name !== binding.name)
75
+ throw new ToolRefusal("repository-mismatch", "the trusted configuration names another repository", 1, {
76
+ repository: binding.id,
77
+ });
78
+ return config;
79
+ }
80
+ const SHA40 = /^[0-9a-f]{40}$/;
81
+ const HEX64 = /^[0-9a-f]{64}$/;
82
+ /** Refuses malformed remote bindings, and an id used by a local and a remote binding alike. */
83
+ export function assertRemoteBindings(remote, local) {
84
+ const seen = new Set(local.map((b) => b.id));
85
+ for (const b of remote) {
86
+ if (!ID.test(b.id))
87
+ throw new Error(`repository id ${JSON.stringify(b.id)} is malformed`);
88
+ if (seen.has(b.id))
89
+ throw new Error(`repository id ${b.id} is listed twice`);
90
+ seen.add(b.id);
91
+ if (!/^[A-Za-z0-9_.-]{1,100}$/.test(b.owner) || !/^[A-Za-z0-9_.-]{1,100}$/.test(b.name))
92
+ throw new Error(`repository ${b.id}: owner and name must be GitHub names`);
93
+ if (b.configSha256 !== undefined && !HEX64.test(b.configSha256))
94
+ throw new Error(`repository ${b.id}: configSha256 must be 64 lowercase hex characters`);
95
+ }
96
+ }
97
+ export function resolveRemoteBinding(remote, principal, id) {
98
+ const binding = remote.find((b) => b.id === id);
99
+ const allowed = principal.repositories === "*" || principal.repositories.includes(id);
100
+ return binding && allowed ? binding : null;
101
+ }
102
+ /** The snapshot's own checks: revision shape, age, pin, parse and repository identity. */
103
+ export function checkSnapshot(binding, snapshot, now, maxAgeMs) {
104
+ const detail = { repository: binding.id };
105
+ if (!snapshot || typeof snapshot.text !== "string" || typeof snapshot.revision !== "string")
106
+ throw new ToolRefusal("config-missing", "the host supplied no trusted configuration", 2, detail);
107
+ if (!SHA40.test(snapshot.revision))
108
+ throw new ToolRefusal("config-invalid", "the trusted revision is not a full commit SHA", 2, detail);
109
+ if (!Number.isFinite(snapshot.observedAt) ||
110
+ snapshot.observedAt > now + 60_000 ||
111
+ now - snapshot.observedAt > maxAgeMs)
112
+ throw new ToolRefusal("config-stale", "the trusted configuration snapshot is too old", 3, {
113
+ ...detail,
114
+ maxAgeMs,
115
+ });
116
+ if (binding.configSha256 !== undefined && sha256(snapshot.text) !== binding.configSha256)
117
+ throw new ToolRefusal("config-mismatch", "the trusted configuration is not the pinned one", 2, detail);
118
+ let config;
119
+ try {
120
+ config = parseConfig(snapshot.text, "comforge.config.json");
121
+ }
122
+ catch (error) {
123
+ throw new ToolRefusal("config-invalid", "the trusted comforge.config.json is invalid", 2, {
124
+ ...detail,
125
+ reason: error instanceof Error ? error.message.slice(0, 500) : "invalid",
126
+ });
127
+ }
128
+ if (config.repository.owner !== binding.owner || config.repository.name !== binding.name)
129
+ throw new ToolRefusal("repository-mismatch", "the trusted configuration names another repository", 1, detail);
130
+ return config;
131
+ }
132
+ const sha256 = (text) => createHash("sha256").update(text, "utf8").digest("hex");
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
+ }
@@ -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 RemoteHost, type RemoteRepositoryBinding, type RepositoryBinding, type TrustedConfigSnapshot, 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 { REMOTE_READ_TOOLS, 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 { REMOTE_READ_TOOLS, SERVER_NAME, SERVER_VERSION } from "./tools.js";
@@ -0,0 +1,84 @@
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
+ readonly "checkout-required": "the tool needs a repository checkout; this repository is served without one";
37
+ readonly "config-missing": "the host supplied no trusted configuration for this repository";
38
+ readonly "config-stale": "the host's trusted configuration snapshot is older than allowed";
39
+ readonly "config-mismatch": "the configuration is not the pinned one, or not what GitHub holds at its revision";
40
+ };
41
+ /** Replaces every value a caller must never see: the call's credentials and secret-like text. */
42
+ export declare function redact(value: unknown, secrets: readonly string[]): unknown;
43
+ export declare function fromServiceError(error: ServiceError): McpError;
44
+ export declare function fromRefusal(r: ToolRefusal): McpError;
45
+ export declare function internalError(): McpError;
46
+ /** Truncates long strings and caps the serialized size of a value. */
47
+ export declare function bound(value: unknown, maxChars?: number): unknown;
48
+ export declare function excerpt(text: string, detail: boolean): {
49
+ text: string;
50
+ truncated: boolean;
51
+ };
52
+ export interface Page<T> {
53
+ items: T[];
54
+ page: {
55
+ cursor: string;
56
+ next: string | null;
57
+ total: number;
58
+ pageSize: number;
59
+ };
60
+ }
61
+ export declare function paginate<T>(all: readonly T[], cursor?: string, pageSize?: number): Page<T>;
62
+ export interface ToolSuccess {
63
+ schema: typeof RESULT_SCHEMA;
64
+ tool: ToolName;
65
+ ok: true;
66
+ /** @comforge/cli exit class of the result: 0, or 1 for a recorded FAIL (verify). */
67
+ exit: number;
68
+ summary: string;
69
+ data: Record<string, unknown>;
70
+ page?: Page<unknown>["page"];
71
+ }
72
+ export declare function success(tool: ToolName, summary: string, data: Record<string, unknown>, page?: Page<unknown>["page"], exit?: number): ToolSuccess;
73
+ /** A delivery the CLI recorded as incomplete: its code, at the stage that failed. */
74
+ export declare function incompleteDelivery(v: {
75
+ delivery: string;
76
+ attempt?: number;
77
+ failedStage?: string;
78
+ stages: Record<string, unknown>;
79
+ error?: {
80
+ code?: string;
81
+ message: string;
82
+ detail?: unknown;
83
+ };
84
+ }, exit: number): McpError;