@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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,213 @@
1
- # Temporary Holding Version
1
+ # @comforge/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `comforge-mcp` serves the governed agent lifecycle of [`@comforge/cli`](https://www.npmjs.com/package/@comforge/cli)
4
+ over the [Model Context Protocol](https://modelcontextprotocol.io). It calls the CLI's published
5
+ lifecycle services and `@comforge/github`'s reads in process. It never shells out to `comforge`,
6
+ parses its output, or keeps a second copy of its governance, state or authorization.
7
+
8
+ This README describes the source in this repository. Capabilities marked "candidate" depend on
9
+ unreleased candidates of `@comforge/core`, `@comforge/github` and `@comforge/cli`, and on this
10
+ package's own unreleased changes; `package.json` still says 0.1.0 until the version PR.
11
+
12
+ It never merges, deploys, approves, requests a review, closes an issue or runs an arbitrary command.
13
+
14
+ ## Tools
15
+
16
+ | Tool | Profile | What it does |
17
+ |---|---|---|
18
+ | `comforge_capabilities` | all | profiles, repository ids, tools, execution availability, what the server never does |
19
+ | `comforge_context` | all | routes a task through the repository's context manifest |
20
+ | `comforge_status` | all | initiatives, summary first and paginated, or one initiative with counts |
21
+ | `comforge_evidence` | all | one section of an initiative's record (validations, publications, completions, revisions, operations), newest first |
22
+ | `comforge_issue` | all | an issue and whether its specification still verifies, or (without `number`) a page of issues; text is untrusted |
23
+ | `comforge_pr` | all | a pull request, optionally its checks, changed files and native GitHub reviews |
24
+ | `comforge_prs` (candidate) | all | a page of the repository's pull requests (`state` open, closed or all) |
25
+ | `comforge_comments` (candidate) | all | a page of an issue's or pull request's comments; text is untrusted |
26
+ | `comforge_reviews` (candidate) | all | a pull request's advisory reviews, with integrity and provenance |
27
+ | `comforge_artifact` (candidate) | all | one file at an exact commit, only under the repository's trusted `artifacts.readable` paths |
28
+ | `comforge_start` | executor | verifies the specification, creates the isolated checkout |
29
+ | `comforge_revise` | executor | reuses or re-creates a pull request's checkout and syncs it |
30
+ | `comforge_verify` | executor | trusted validation of an exact commit in a clean snapshot |
31
+ | `comforge_deliver` | publisher | push, one pull request, one completion record, read back; `execute:false` plans |
32
+ | `comforge_recover` | publisher | settles uncertain writes from GitHub; `execute:false` reports |
33
+ | `comforge_cleanup` | publisher | plans a cleanup; executing needs operator mode or a cleanup-scoped command grant (candidate; below) |
34
+ | `comforge_publish_review` (candidate) | reviewer | publishes one advisory review comment bound to the reviewed head; `execute:false` plans |
35
+ | `comforge_publish_specification` (candidate) | publisher | publishes a specification issue (idempotent, read back); `execute:false` plans |
36
+
37
+ The candidate contracts total 18 tools. Advisory reviews are marked comments, never native
38
+ reviews or approvals.
39
+ The four profiles are `read-only`, `reviewer` (adds patches and full review bodies to reads),
40
+ `executor` and `publisher`. A principal can hold several. A principal discovers only the tools its
41
+ profiles permit, and every call checks the profile again.
42
+
43
+ ## Contracts
44
+
45
+ Every input object is strict and versioned. An unknown field is refused before a handler runs,
46
+ and so is a forged internal option such as `authorized`, a path, a URL or a credential. A
47
+ repository is named by its allowlisted id.
48
+
49
+ ```text
50
+ success {schema:"comforge-mcp/v1", tool, ok:true, exit, summary, data, page?}
51
+ refusal {schema:"comforge-mcp-error/v1", code, message, exit, retryable, hint?, detail?}
52
+ ```
53
+
54
+ `exit` is the CLI's exit class: 0 ok, 1 refused, 2 usage or configuration, 3 failed, 4 incomplete.
55
+ Results are bounded: about 48,000 characters each, and untrusted text is excerpted unless a
56
+ reviewer asks for detail. Longer lists are paginated with `cursor` and `pageSize`. Credentials
57
+ and secret-like text are redacted. Over HTTP, host paths are replaced by `<host>`.
58
+
59
+ ## Security model
60
+
61
+ - **Credentials are server-owned.** The host provides them per repository and principal, or they
62
+ come from the repository's trusted `security.credentials` source. They are never returned.
63
+ - **Authorization stays in `@comforge/cli`.** Writes need the repository's trusted
64
+ `security.authorization`: owner grants or operator mode. A caller passes an owner-signed grant
65
+ envelope in `grant`, and the CLI verifies it against the trusted keys, ticket, specification,
66
+ head and branch. The server cannot authorize anything itself.
67
+ - **Cleanup needs its own authority (candidate).** `comforge_cleanup` with `execute:true` runs
68
+ under operator mode, or under an owner grant that scopes the command to cleanup of the merged
69
+ pull request (`authorizeCommand` in [`@comforge/core`](https://www.npmjs.com/package/@comforge/core)). A grant signed
70
+ to publish is never valid for cleanup. With the published `@comforge/core` 0.1.x grant format,
71
+ which cannot name a command, `execute:true` is refused with `command-scope-unsupported`; run
72
+ cleanup through the `comforge` CLI.
73
+ - **Repository isolation.** Each principal has an allowlist. An unknown or foreign id gets the same
74
+ refusal, and the trusted configuration must name the bound GitHub repository.
75
+ - **Local stdio.** The trust boundary is the local user. The operator picks the repositories and
76
+ profiles at launch, and there is no authentication. Repository commands run in the server's
77
+ process environment, as `comforge` would.
78
+ - **Streamable HTTP.** The host mounts `createHttpHandler(options)` and authenticates each request,
79
+ returning a principal or `null`. Before any MCP message is parsed, the handler checks:
80
+ 1. the `Host` allowlist;
81
+ 2. the `Origin` allowlist;
82
+ 3. the method;
83
+ 4. the body size;
84
+ 5. authentication, with a `WWW-Authenticate` challenge on 401;
85
+ 6. the per-principal rate and concurrency limits.
86
+
87
+ Sessions are created by `initialize`, bound to their principal and expire when idle. Any other
88
+ principal presenting the session id is refused.
89
+ - **Remote execution is off by default.** Over HTTP, the tools that run repository commands
90
+ (start, revise, verify, deliver, recover, cleanup) are neither listed nor callable unless the
91
+ host passes an `IsolationProvider`. That is the host's attestation that its runtime runs every
92
+ command inside an isolation boundary it operates. A flag cannot stand in for it. This package
93
+ implements no sandbox and claims none.
94
+ - **Remote publication is not remote execution (candidate).** The reads, `comforge_publish_review`
95
+ and `comforge_publish_specification` run no repository command, so over HTTP they are available
96
+ without an `IsolationProvider`. They still need the principal's profile and the repository's
97
+ trusted authorization. Only the executing tools need the provider.
98
+ - **Host policy (candidate).** `HostServices.hostPolicy(binding)` hands the CLI's `HostPolicy`
99
+ (checkout parent, worker preparation and removal, validation) to the lifecycle for one
100
+ repository. It is host code; no tool input reaches it.
101
+ - **Cancellation.** It is checked between the CLI's stages, never in the middle of a write. An
102
+ interrupted delivery is recorded and settled by `comforge_recover`.
103
+
104
+ ## Deploying the HTTP handler
105
+
106
+ - **Terminate TLS in front of it.** The handler checks the `Host` header against `allowedHosts`
107
+ and the `Origin` header against `allowedOrigins`. It never reads `X-Forwarded-*`. A reverse
108
+ proxy must forward the original `Host`, and the host's `authenticate` must not trust
109
+ client-supplied identity headers that the proxy does not set.
110
+ - **Each request is authenticated,** including session reuse, the SSE `GET` and `DELETE`.
111
+ - A session belongs to the principal that initialized it.
112
+ - A different principal is refused.
113
+ - If the same principal comes back with other profiles or repositories, the session ends,
114
+ and the client starts a new one. A revoked principal gets 401 at once.
115
+ - An authenticator that throws is treated as no principal.
116
+ - **Limits are per process.** Rate, concurrency and session limits and the session table live in
117
+ one process, so a multi-instance deployment needs sticky sessions and limits enforced in front.
118
+ - **Repository commands are synchronous.** They block the process for their duration (see
119
+ Limits). Remote execution belongs on host-operated workers that the `IsolationProvider`
120
+ stands for.
121
+ - `compactDiscovery: true` (or `--compact-discovery`) leaves the output schemas out of
122
+ `tools/list`. Measured: 39-45% fewer discovery tokens (17 tools: 11,019 to 6,759). The results
123
+ keep the same versioned envelope.
124
+ - `textContent: "summary"` (candidate; `--summary-text`; default `"full"`) makes each result's text
125
+ content one summary line and leaves `structuredContent` unchanged. Measured: a model that is
126
+ given `structuredContent` reads the same tokens; the wire shrinks to about the structured size.
127
+ A client that reads only text sees just the summary line, so it is opt-in.
128
+
129
+ Measurements are per-call tokenizer counts on one repository. Equivalent initiative state still costs more through MCP
130
+ than through the CLI (4,224 vs 3,701 tokens for every initiative's status); for the new reads MCP
131
+ is the smallest equivalent form (pull requests 1,191 vs CLI 1,617 vs raw GitHub 2,587). Discovery
132
+ is the largest fixed cost of an MCP session. These are per-call counts; no end-to-end saving is
133
+ claimed.
134
+
135
+ ## Repositories without a checkout (candidate)
136
+
137
+ A host that has no checkout (a web app that answers MCP over HTTP) can still serve the GitHub
138
+ evidence reads: `comforge_capabilities`, `comforge_issue`, `comforge_pr`, `comforge_prs`,
139
+ `comforge_comments`, `comforge_reviews` and `comforge_artifact` (`REMOTE_READ_TOOLS`).
140
+
141
+ ```ts
142
+ createHttpHandler({
143
+ repositories: [],
144
+ remoteRepositories: [{ id: "widgets", owner: "acme", name: "widgets", configSha256: "<optional pin>" }],
145
+ remote: {
146
+ trustedConfig: async (b) => ({ revision, text, observedAt }), // host code: the base head and its comforge.config.json
147
+ credentials: (b, principal) => serverOwnedToken,
148
+ configMaxAgeMs: 600_000,
149
+ },
150
+ host: { runtime: () => { throw new Error("no runtime"); } },
151
+ // authenticate, allowedHosts, ... as above
152
+ });
153
+ ```
154
+
155
+ - The host supplies the trusted configuration; a caller never can. The server refuses a
156
+ snapshot whose revision is not a full SHA (`config-invalid`), that is older than
157
+ `configMaxAgeMs` or from the future (`config-stale`, retryable), that differs from the pin or
158
+ from GitHub's bytes at that revision read with the server's credential (`config-mismatch`), or
159
+ that names another repository (`repository-mismatch`). A source that throws is `config-missing`.
160
+ - Whether the revision is the base branch head is the host's statement; the server verifies the
161
+ bytes at that revision, not branch membership.
162
+ - Every other tool is refused for such a repository with `checkout-required`, with or without an
163
+ `IsolationProvider`: loading a configuration never enables execution or writes. A server with
164
+ only checkout-free repositories does not list those tools at all.
165
+
166
+ ## Signed command scope (candidate)
167
+
168
+ `@comforge/core` adds an optional signed `commands` list to a grant, and `@comforge/cli` checks it:
169
+ - a grant **without** the field keeps its meaning for publish, complete, deliver and recover;
170
+ - such a grant is **never** valid for cleanup;
171
+ - a grant **with** the field is valid only for the commands it lists.
172
+
173
+ `comforge_cleanup` executes under operator mode or such a scoped grant, once these candidates are
174
+ released and pinned. The grant format is documented in the
175
+ [`@comforge/core` README](https://www.npmjs.com/package/@comforge/core).
176
+
177
+ ## Run locally
178
+
179
+ ```sh
180
+ npx comforge-mcp --repository . --profile executor --profile publisher
181
+ ```
182
+
183
+ Repository ids are the configured repository names. The default profile is `read-only`.
184
+
185
+ ## Embed
186
+
187
+ ```ts
188
+ import { createHttpHandler } from "@comforge/mcp";
189
+
190
+ const handler = createHttpHandler({
191
+ repositories: [{ id: "widgets", root: "/srv/widgets", owner: "acme", name: "widgets" }],
192
+ host: { runtime: (b) => myRuntime(b.root), credentials: (b, p) => () => tokenFor(b, p) },
193
+ authenticate: async (req) => principalFromBearer(req), // { id, profiles, repositories } | null
194
+ allowedHosts: ["mcp.acme.example"],
195
+ allowedOrigins: ["https://agents.acme.example"],
196
+ });
197
+ // Bun.serve({ fetch: (req) => handler.handle(req) }), or any web-standard Request/Response host.
198
+ ```
199
+
200
+ `createComforgeMcpServer` gives you an `McpServer` for one principal, to use with any transport.
201
+ `serveStdio` connects that server to stdio.
202
+
203
+ ## Limits
204
+
205
+ - **Repository commands block their process.** They run synchronously through the CLI's runtime,
206
+ so a long validation holds the server for its duration. That is one more reason remote
207
+ execution needs a host-operated worker.
208
+ - **Advisory reviews need the candidates.** Advisory reviews (marked comments) are not readable
209
+ through the published `@comforge/github`; with it, `comforge_pr` returns native GitHub reviews
210
+ only and says so. `comforge_reviews` and `comforge_publish_review` need the `@comforge/github`
211
+ and `@comforge/cli` candidates and the repository's `review` configuration section.
212
+ - **Limits are per process.** Rate and session limits live in one process, so run one instance
213
+ per limit domain.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `comforge-mcp`: a local stdio server over one or more repositories.
4
+ *
5
+ * comforge-mcp [--repository DIR]... [--profile read-only|reviewer|executor|publisher]... [--compact-discovery] [--summary-text]
6
+ *
7
+ * Defaults: the current directory's repository and the read-only profile. The operator
8
+ * chooses both at launch; a caller can never widen them. Credentials come from each
9
+ * repository's trusted `security.credentials` source (an environment variable or `gh`),
10
+ * read by this process and never returned.
11
+ */
12
+ import path from "node:path";
13
+ import { defaultRuntime, parseConfig } from "@comforge/cli";
14
+ import { PROFILES } from "./contracts.js";
15
+ import { serveStdio } from "./stdio.js";
16
+ function usage(message) {
17
+ process.stderr.write(`comforge-mcp: ${message}\nusage: comforge-mcp [--repository DIR]... [--profile ${PROFILES.join("|")}]... [--compact-discovery] [--summary-text]\n`);
18
+ process.exit(2);
19
+ }
20
+ const argv = process.argv.slice(2);
21
+ if (argv.includes("--help"))
22
+ usage("help");
23
+ const compactDiscovery = argv.includes("--compact-discovery");
24
+ const summaryText = argv.includes("--summary-text");
25
+ const args = argv.filter((a) => a !== "--compact-discovery" && a !== "--summary-text");
26
+ const dirs = [];
27
+ const profiles = [];
28
+ for (let i = 0; i < args.length; i += 2) {
29
+ const [flag, value] = [args[i], args[i + 1]];
30
+ if (!value)
31
+ usage(`${flag} needs a value`);
32
+ if (flag === "--repository")
33
+ dirs.push(path.resolve(value));
34
+ else if (flag === "--profile") {
35
+ if (!PROFILES.includes(value))
36
+ usage(`unknown profile ${value}`);
37
+ profiles.push(value);
38
+ }
39
+ else
40
+ usage(`unknown option ${flag}`);
41
+ }
42
+ const base = defaultRuntime();
43
+ const git = (cwd, ...a) => {
44
+ const r = base.run("git", a, { cwd });
45
+ if (r.status !== 0)
46
+ usage(`${cwd} is not a Git repository`);
47
+ return r.stdout.trim();
48
+ };
49
+ const bindings = (dirs.length > 0 ? dirs : [process.cwd()]).map((dir) => {
50
+ const root = git(dir, "rev-parse", "--show-toplevel");
51
+ const commonDir = path.resolve(root, git(root, "rev-parse", "--git-common-dir"));
52
+ const shown = base.run("git", ["show", "refs/remotes/origin/HEAD:comforge.config.json"], {
53
+ cwd: root,
54
+ });
55
+ const fallback = shown.status === 0
56
+ ? shown
57
+ : base.run("git", ["show", "refs/remotes/origin/main:comforge.config.json"], { cwd: root });
58
+ if (fallback.status !== 0)
59
+ usage(`${root} has no comforge.config.json on its base branch`);
60
+ const config = parseConfig(fallback.stdout, "comforge.config.json");
61
+ const id = config.repository.name
62
+ .toLowerCase()
63
+ .replace(/[^a-z0-9._-]/g, "-")
64
+ .slice(0, 64);
65
+ return { id, root, commonDir, owner: config.repository.owner, name: config.repository.name };
66
+ });
67
+ await serveStdio({
68
+ repositories: bindings,
69
+ principal: {
70
+ id: "local",
71
+ profiles: profiles.length > 0 ? profiles : ["read-only"],
72
+ repositories: "*",
73
+ },
74
+ host: { runtime: (b) => ({ ...base, cwd: b.root }) },
75
+ ...(compactDiscovery ? { compactDiscovery: true } : {}),
76
+ ...(summaryText ? { textContent: "summary" } : {}),
77
+ });