@zabaca/zbc 0.20.0 → 0.21.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/package.json +1 -1
- package/templates/apps/walgit/CONTEXT.md +12 -0
- package/templates/apps/walgit/README.md +41 -0
- package/templates/apps/walgit/package.json +5 -1
- package/templates/apps/walgit/registry.json +1 -1
- package/templates/apps/walgit/shared/llms.ts +16 -0
- package/templates/apps/walgit/shared/mcp.ts +286 -0
- package/templates/apps/walgit/shared/protocol.ts +20 -0
- package/templates/apps/walgit/shared/telemetry.ts +11 -0
- package/templates/apps/walgit/worker/index.ts +46 -0
- package/templates/apps/walgit/worker/mcp.ts +281 -0
package/package.json
CHANGED
|
@@ -197,3 +197,15 @@ not exist at all on a deployment that does not offer Proposals. *Superseded* is
|
|
|
197
197
|
deliberately not reported: ADR-0018 admits it only if the same walk yields it
|
|
198
198
|
free, and it does not.
|
|
199
199
|
_Avoid_: list endpoint, PR list, the proposals API
|
|
200
|
+
|
|
201
|
+
## The MCP endpoint
|
|
202
|
+
|
|
203
|
+
**MCP Endpoint**:
|
|
204
|
+
`/_walgit/mcp` — a Model Context Protocol server over Streamable HTTP, answered at the edge on every deployment (`shared/mcp.ts`, transported by `worker/mcp.ts`). The rule that decides what belongs on it: **it carries only what the host can answer without the agent's disk** — `agentgit_status` (a name's existence, its Claim, its Reader List, its refs), `agentgit_watch` (block until a ref moves), `agentgit_provenance` (who signed the push that moved one), and the manual as the resource `agentgit://manual`. Accepting a Proposal, writing a credential helper and fetching into a clone act on a tree the host cannot see, so they stay client commands.
|
|
205
|
+
_Avoid_: "the API" — it is one more way to ask the questions the existing routes answer, not a second surface with its own answers.
|
|
206
|
+
|
|
207
|
+
**The gate is not copied**:
|
|
208
|
+
The MCP reads reach the host's own gated routes rather than re-deciding anything: `agentgit_status` and `agentgit_provenance` go through `PROVENANCE_PATH` (the deployment credential, then the Read Challenge on a Private name), and `agentgit_watch` subscribes to the **Fan-out** the way a **Watch** client does. A refusal is forwarded verbatim and is the *whole* answer — a Private name an unproven reader asked about leaks no refs, no existence and no lists alongside its 401, which is the property `info/refs` has.
|
|
209
|
+
|
|
210
|
+
**The watch cap**:
|
|
211
|
+
`agentgit_watch` holds a Worker request open, so the five-minute deadline is the **host's** and not the caller's: a longer `timeoutMs` is clamped, not honoured. Reaching it answers `{ timedOut: true }` — an answer, never an error — and calling again loses nothing, because a **Ref Event** is latest state and the next call is current state rather than a replay (ADR-0009).
|
|
@@ -434,6 +434,47 @@ A repository is created on first contact: pushing to a name nobody has used
|
|
|
434
434
|
creates it, with `receive.unpackLimit=0` so even a tiny push is retained as a
|
|
435
435
|
packfile (what the WAL will upload).
|
|
436
436
|
|
|
437
|
+
### The MCP endpoint
|
|
438
|
+
|
|
439
|
+
`/_walgit/mcp` is a Model Context Protocol server over Streamable HTTP
|
|
440
|
+
(`shared/mcp.ts` builds it, `worker/mcp.ts` transports it), answered at the edge
|
|
441
|
+
on every deployment. An MCP client reaches it by URL — nothing to install,
|
|
442
|
+
nothing to spawn:
|
|
443
|
+
|
|
444
|
+
```bash
|
|
445
|
+
claude mcp add --transport http agentgit https://<worker-host>/_walgit/mcp
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
It carries only what the host can answer **without the agent's disk**:
|
|
449
|
+
|
|
450
|
+
| tool | what it answers |
|
|
451
|
+
| --- | --- |
|
|
452
|
+
| `agentgit_status` | does a name exist, is it claimed, is it private, and its refs |
|
|
453
|
+
| `agentgit_watch` | blocks until a ref moves; `{ ref, sha }` or `{ timedOut: true }`, capped at five minutes per call |
|
|
454
|
+
| `agentgit_provenance` | which key signed the push that moved a ref |
|
|
455
|
+
|
|
456
|
+
plus `agentgit://manual` as a resource — the same `renderLlms` output `/llms.txt`
|
|
457
|
+
serves, from the same capabilities.
|
|
458
|
+
|
|
459
|
+
The gate is the host's own and never a second copy: `status` and `provenance`
|
|
460
|
+
both go through the container's `PROVENANCE_PATH`, which already sits behind
|
|
461
|
+
exactly the credential a clone needs and already applies the Read Challenge for
|
|
462
|
+
a Private name, so an unproven reader is refused there and the refusal is
|
|
463
|
+
forwarded verbatim. `watch` subscribes to the ref-event Durable Object exactly
|
|
464
|
+
as a WebSocket client does, so the Reader List is judged by the same code that
|
|
465
|
+
judges a subscription — and it needs the event stream configured, saying so
|
|
466
|
+
where it is not.
|
|
467
|
+
|
|
468
|
+
Which means `status` and `provenance` **do** wake the container, and `status`
|
|
469
|
+
twice (the gated provenance read, then `REFS_PATH`). Refs are authoritative in
|
|
470
|
+
the Index, the Index is reachable only with the container's object-store
|
|
471
|
+
credentials, and the gate is the container's — an edge answer would need a
|
|
472
|
+
second verifier and a second reader, which is what
|
|
473
|
+
[ADR-0013](../../../../../docs/adr/0013-a-name-can-refuse-a-stranger-reading.md)
|
|
474
|
+
and [ADR-0007](../../../../../docs/adr/0007-walgit-object-storage-holds-the-log.md)
|
|
475
|
+
each refuse. The protocol itself, `agentgit_watch` and the manual are answered
|
|
476
|
+
at the edge and touch it not at all.
|
|
477
|
+
|
|
437
478
|
## Deployment
|
|
438
479
|
|
|
439
480
|
Through the `cloudflare` module, never by hand — `zbc apply <env>`. The Worker
|
|
@@ -18,7 +18,11 @@
|
|
|
18
18
|
"deploy": "wrangler deploy"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"
|
|
21
|
+
"@hono/mcp": "^0.3.1",
|
|
22
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
23
|
+
"aws4fetch": "^1.0.20",
|
|
24
|
+
"hono": "^4.12.30",
|
|
25
|
+
"zod": "^4.4.3"
|
|
22
26
|
},
|
|
23
27
|
"devDependencies": {
|
|
24
28
|
"@cloudflare/containers": "^0.3.7",
|
|
@@ -17,5 +17,5 @@
|
|
|
17
17
|
],
|
|
18
18
|
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
19
19
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
20
|
-
"instructions": "STATUS: the front door and the push path are deployable — a Cloudflare Worker proxying to a Durable-Object-bound Container that serves git smart-HTTP, with every push persisted to the write-ahead log in object storage before it is acknowledged and linearized by compare-and-swap on index.json. The bare repos on the container's filesystem are a cache, reconciled against the log on every access and materialized from it when the objects a ref needs are absent. A repo whose cache is gone is rebuilt from the log on first access — not disaster recovery but the normal path, since the container sleeps when idle and its disk is wiped completely on every restart. The log is compacted in the background: once a repo accumulates WALGIT_COMPACTION_THRESHOLD (default 50) un-superseded entries, a post-receive hook hands a detached process a `git repack -adf` whose single pack is published as one WAL entry under a per-repo lease, so a cold restore replays one entry however many pushes the repo has taken. Superseded entries and the packs rejected pushes leave behind are deleted only after WALGIT_GC_GRACE_MS (default one hour), never immediately — a restore that read index.json a moment before a compaction is still downloading what that compaction superseded, and deleting it out from under that restore fails silently. Both knobs are optional environment variables, not secrets.\n\nTRANSPORT: smart-HTTP only. walgit used to also serve SSH, which needed raw inbound TCP and is why it ran on Fly (docs/adr/0006 in the zbc repository); no Cloudflare product delivers raw inbound TCP, so the SSH transport was removed rather than kept on a second host. Clients send the token as the Basic-auth password: `git clone https://walgit:$TOKEN@<worker-host>/myrepo.git`. A repository is created on first push to a name nobody has used.\n\nDEPLOYMENT: through the `cloudflare` module. `wrangler deploy` builds the container image from this package's Dockerfile, so Docker must be running at apply time and the account must be on a Workers Paid plan with Containers enabled. Set `immediateContainerRollout: true` on the instance — wrangler's gradual rollout never drains a single always-warm container, so a redeployed image otherwise never takes effect until it idle-sleeps. That flag covers the IMAGE only; a deploy that changes only forwarded env vars produces no new container version to roll, and the container reads its environment once at start — so the Durable Object fingerprints the environment it would boot with, keeps it in DO storage, and destroys the running container the first time the two differ (reconcileEnv in worker/index.ts). Changing a var therefore costs one container restart on the next request and takes effect immediately. CLOUDFLARE_API_TOKEN needs Workers Scripts: Edit and Containers: Edit. Trap when tearing one down: `wrangler delete` on the Worker does NOT delete its container application — that needs a separate `wrangler containers delete`, or the instances stay live.\n\nCONFIGURATION: the container runs outside the Worker's binding graph, so it reads the store over the S3 API rather than through an r2 binding, and it can only be told about it via environment variables the Worker forwards (CONTAINER_ENV in shared/container-env.ts). Wire these as the cloudflare instance's `workerSecrets`: WALGIT_HTTP_TOKENS (comma-separated bearer tokens, comma-separated so a credential can be rotated without a window where neither works), and the log's home — WALGIT_S3_ENDPOINT, WALGIT_S3_BUCKET, WALGIT_S3_ACCESS_KEY_ID and WALGIT_S3_SECRET_ACCESS_KEY, from an r2 module instance's S3-API credentials. Without those four the host still serves reads from its local cache but REFUSES every push — accepting one it cannot persist is the single failure this app exists to prevent. A secret that is not in that forward list reaches the Worker and stops there.\n\nOPERATOR CLI: src/cli.ts — `bun src/cli.ts <serve|materialize|verify|gc|compact>`, run inside the container so it reads the same credentials the app does; there is no separate config file. `verify` is read-only and exits non-zero when the disk disagrees with index.json; `gc` reclaims superseded and orphaned objects and only reports unless given --yes; `compact` forces a compaction now rather than waiting for the threshold, and `--force=false` asks whether one is due without causing it.\n\nREF EVENTS: optional, off unless configured. Set WALGIT_EVENTS_URL (the deployment's own public origin) and WALGIT_EVENTS_TOKEN (a shared secret, wired as a workerSecret and forwarded to the container) and walgit serves a WebSocket at /_walgit/events: a client sends {\"watch\":[{\"repo\":\"my-thing\",\"refs\":[\"refs/heads/main\"]}]}, is answered with the current sha of each watched ref, and is then sent the new sha every time one moves (sha null is a deletion; an omitted refs list watches every ref in that repository). Subscribing takes exactly the credential a read takes, so a public deployment has a public stream. Events are latest state, not a log — no cursor, no since, no sequence number on the wire; a reconnecting client gets current state in its handshake. The push path announces from post-receive, which git runs only after the compare-and-swap on index.json won, so a push that lost is never announced; the announcement is authenticated, bounded, and can never fail a push. With either variable unset the endpoint does not exist."
|
|
20
|
+
"instructions": "STATUS: the front door and the push path are deployable — a Cloudflare Worker proxying to a Durable-Object-bound Container that serves git smart-HTTP, with every push persisted to the write-ahead log in object storage before it is acknowledged and linearized by compare-and-swap on index.json. The bare repos on the container's filesystem are a cache, reconciled against the log on every access and materialized from it when the objects a ref needs are absent. A repo whose cache is gone is rebuilt from the log on first access — not disaster recovery but the normal path, since the container sleeps when idle and its disk is wiped completely on every restart. The log is compacted in the background: once a repo accumulates WALGIT_COMPACTION_THRESHOLD (default 50) un-superseded entries, a post-receive hook hands a detached process a `git repack -adf` whose single pack is published as one WAL entry under a per-repo lease, so a cold restore replays one entry however many pushes the repo has taken. Superseded entries and the packs rejected pushes leave behind are deleted only after WALGIT_GC_GRACE_MS (default one hour), never immediately — a restore that read index.json a moment before a compaction is still downloading what that compaction superseded, and deleting it out from under that restore fails silently. Both knobs are optional environment variables, not secrets.\n\nTRANSPORT: smart-HTTP only. walgit used to also serve SSH, which needed raw inbound TCP and is why it ran on Fly (docs/adr/0006 in the zbc repository); no Cloudflare product delivers raw inbound TCP, so the SSH transport was removed rather than kept on a second host. Clients send the token as the Basic-auth password: `git clone https://walgit:$TOKEN@<worker-host>/myrepo.git`. A repository is created on first push to a name nobody has used.\n\nDEPLOYMENT: through the `cloudflare` module. `wrangler deploy` builds the container image from this package's Dockerfile, so Docker must be running at apply time and the account must be on a Workers Paid plan with Containers enabled. Set `immediateContainerRollout: true` on the instance — wrangler's gradual rollout never drains a single always-warm container, so a redeployed image otherwise never takes effect until it idle-sleeps. That flag covers the IMAGE only; a deploy that changes only forwarded env vars produces no new container version to roll, and the container reads its environment once at start — so the Durable Object fingerprints the environment it would boot with, keeps it in DO storage, and destroys the running container the first time the two differ (reconcileEnv in worker/index.ts). Changing a var therefore costs one container restart on the next request and takes effect immediately. CLOUDFLARE_API_TOKEN needs Workers Scripts: Edit and Containers: Edit. Trap when tearing one down: `wrangler delete` on the Worker does NOT delete its container application — that needs a separate `wrangler containers delete`, or the instances stay live.\n\nCONFIGURATION: the container runs outside the Worker's binding graph, so it reads the store over the S3 API rather than through an r2 binding, and it can only be told about it via environment variables the Worker forwards (CONTAINER_ENV in shared/container-env.ts). Wire these as the cloudflare instance's `workerSecrets`: WALGIT_HTTP_TOKENS (comma-separated bearer tokens, comma-separated so a credential can be rotated without a window where neither works), and the log's home — WALGIT_S3_ENDPOINT, WALGIT_S3_BUCKET, WALGIT_S3_ACCESS_KEY_ID and WALGIT_S3_SECRET_ACCESS_KEY, from an r2 module instance's S3-API credentials. Without those four the host still serves reads from its local cache but REFUSES every push — accepting one it cannot persist is the single failure this app exists to prevent. A secret that is not in that forward list reaches the Worker and stops there.\n\nOPERATOR CLI: src/cli.ts — `bun src/cli.ts <serve|materialize|verify|gc|compact>`, run inside the container so it reads the same credentials the app does; there is no separate config file. `verify` is read-only and exits non-zero when the disk disagrees with index.json; `gc` reclaims superseded and orphaned objects and only reports unless given --yes; `compact` forces a compaction now rather than waiting for the threshold, and `--force=false` asks whether one is due without causing it.\n\nREF EVENTS: optional, off unless configured. Set WALGIT_EVENTS_URL (the deployment's own public origin) and WALGIT_EVENTS_TOKEN (a shared secret, wired as a workerSecret and forwarded to the container) and walgit serves a WebSocket at /_walgit/events: a client sends {\"watch\":[{\"repo\":\"my-thing\",\"refs\":[\"refs/heads/main\"]}]}, is answered with the current sha of each watched ref, and is then sent the new sha every time one moves (sha null is a deletion; an omitted refs list watches every ref in that repository). Subscribing takes exactly the credential a read takes, so a public deployment has a public stream. Events are latest state, not a log — no cursor, no since, no sequence number on the wire; a reconnecting client gets current state in its handshake. The push path announces from post-receive, which git runs only after the compare-and-swap on index.json won, so a push that lost is never announced; the announcement is authenticated, bounded, and can never fail a push. With either variable unset the endpoint does not exist.\n\nMCP: the deployment answers the Model Context Protocol at /_walgit/mcp (Streamable HTTP), at the edge and on every deployment — there is no variable to set and nothing to install. `claude mcp add --transport http agentgit https://<host>/_walgit/mcp`. It carries only what the host can answer without the caller's disk: agentgit_status (does a name exist, is it claimed, is it private, and its refs), agentgit_watch (blocks until a ref moves, five minutes per call), agentgit_provenance (which key signed the push that moved a ref), and the /llms.txt manual as the resource agentgit://manual. agentgit_status and agentgit_provenance read through the same gate a clone passes, so a Private name refuses an unproven reader exactly as info/refs does; agentgit_watch needs the ref-event stream above and says so where it is unconfigured."
|
|
21
21
|
}
|
|
@@ -29,6 +29,7 @@ import { CONTENT_SIGNAL } from './robots'
|
|
|
29
29
|
import {
|
|
30
30
|
CHALLENGE_PATH,
|
|
31
31
|
EVENTS_PATH,
|
|
32
|
+
MCP_PATH,
|
|
32
33
|
PROVENANCE_PATH,
|
|
33
34
|
READ_CHALLENGE_NAMESPACE,
|
|
34
35
|
SIGNERS_REF,
|
|
@@ -802,6 +803,21 @@ git clone https://${host}/$NAME.git
|
|
|
802
803
|
\`\`\`
|
|
803
804
|
|
|
804
805
|
Handing work to another agent is the URL and nothing else. There is no owner to ask, no invitation to send and no review to pass.
|
|
806
|
+
|
|
807
|
+
## Ask this host directly
|
|
808
|
+
|
|
809
|
+
This host speaks the Model Context Protocol at \`https://${host}${MCP_PATH}\` (Streamable HTTP). There is nothing to install and nothing to spawn — point a client at the URL:
|
|
810
|
+
|
|
811
|
+
\`\`\`sh
|
|
812
|
+
claude mcp add --transport http agentgit https://${host}${MCP_PATH}
|
|
813
|
+
\`\`\`
|
|
814
|
+
|
|
815
|
+
It carries what this host can answer without your disk: \`agentgit_status\` (does a name exist, is it claimed, is it private, what are its refs), \`agentgit_watch\` (block until a ref moves — the handoff primitive, capped at five minutes per call)${
|
|
816
|
+
// Named only where a signature can be made. On a deployment with no nonce
|
|
817
|
+
// seed the tool answers `signer: null` for every ref, which is the honest
|
|
818
|
+
// answer and a useless one to send an agent after.
|
|
819
|
+
caps.signedPushes ? ', `agentgit_provenance` (which key signed the push that moved a ref)' : ''
|
|
820
|
+
}, and this document as the resource \`agentgit://manual\`. Everything that touches a clone stays a shell command, because this host cannot see your tree.
|
|
805
821
|
${signing}${ownership}${privacy}${proposing}${events}
|
|
806
822
|
## If a push is refused
|
|
807
823
|
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Model Context Protocol surface, as a value.
|
|
3
|
+
*
|
|
4
|
+
* An agent finds a tool through the registry its harness already reads. The
|
|
5
|
+
* first version of this shipped as a stdio server an agent's harness spawned
|
|
6
|
+
* (`npx -y @zabaca/agentgit mcp`), and both ways it could fail to start were
|
|
7
|
+
* spawn problems rather than protocol ones: a cold npx cache racing the
|
|
8
|
+
* client's startup timeout, and a workspace checkout resolving the unlinked
|
|
9
|
+
* package. A URL has neither failure mode, so the server moved to the host
|
|
10
|
+
* that already answers every other question about a repository.
|
|
11
|
+
*
|
|
12
|
+
* **It carries only what the host can answer without the agent's disk.** A
|
|
13
|
+
* name's state, a ref moving, who pushed it, and the manual. Accepting a
|
|
14
|
+
* Proposal, configuring a credential helper and fetching into a clone are the
|
|
15
|
+
* skill's, as shell commands — they act on a tree this process cannot see, and
|
|
16
|
+
* a tool that pretended otherwise would be a tool that could only fail.
|
|
17
|
+
*
|
|
18
|
+
* Nothing here reaches anything. Every fact comes through `McpDeps`, whose
|
|
19
|
+
* implementations (`worker/mcp.ts`) are the container round trip and the event
|
|
20
|
+
* socket — which is what lets the whole surface be driven by a real MCP client
|
|
21
|
+
* in `src/mcp.test.ts` with no runtime at all. `shared/`'s one rule holds: this
|
|
22
|
+
* module imports no runtime, and both halves may compile it (docs/adr/0010).
|
|
23
|
+
*
|
|
24
|
+
* **The names are protocol, not an opinion.** `walgit may gain capabilities,
|
|
25
|
+
* never opinions` (CONTEXT.md), and `agentgit_*` plus `agentgit://manual` look
|
|
26
|
+
* like one deployment's brand in the mechanism. They are not configurable for
|
|
27
|
+
* the same reason `refs/walgit/signers` is not: a client TYPES them. A skill,
|
|
28
|
+
* a plugin and a harness config all name a tool, so a deployment that renamed
|
|
29
|
+
* its tools would be a deployment no existing client can call — the opposite
|
|
30
|
+
* of what instance configuration is for. What IS per-deployment — the host,
|
|
31
|
+
* the capabilities, the operator, every limit in the manual — arrives through
|
|
32
|
+
* `McpDeps`, and every refusal below is prefixed `walgit:` like the rest of
|
|
33
|
+
* this package, because the mechanism is what refused.
|
|
34
|
+
*
|
|
35
|
+
* The one rule it DOES own is the refusal: a read that the host refused is
|
|
36
|
+
* reported as a refusal and nothing else. `status` on a Private name a caller
|
|
37
|
+
* cannot prove a key for must not leak refs, existence or the lists alongside
|
|
38
|
+
* the 401 — that is the property `info/refs` has, and the reason both reading
|
|
39
|
+
* tools go through the host's own gated routes rather than a second copy of
|
|
40
|
+
* the gate.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
44
|
+
import { z } from 'zod'
|
|
45
|
+
|
|
46
|
+
import type { Capabilities } from './capabilities'
|
|
47
|
+
import { renderLlms } from './llms'
|
|
48
|
+
import type { Operator } from './operator'
|
|
49
|
+
import { REF_NAME, REPO_ID } from './protocol'
|
|
50
|
+
|
|
51
|
+
/** The manual, as a resource a client can read without calling a tool. */
|
|
52
|
+
export const MANUAL_URI = 'agentgit://manual'
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The longest a single `agentgit_watch` holds a request open.
|
|
56
|
+
*
|
|
57
|
+
* A watch is a long poll over the ref-event stream, and the request it holds
|
|
58
|
+
* open is a Worker invocation — so the cap is the HOST's, not the caller's. A
|
|
59
|
+
* client that wants to wait longer calls again, and loses nothing by it:
|
|
60
|
+
* events are latest-state, so the next call's answer is current state rather
|
|
61
|
+
* than a replay it might have missed (docs/adr/0009).
|
|
62
|
+
*/
|
|
63
|
+
export const MAX_WATCH_MS = 5 * 60_000
|
|
64
|
+
|
|
65
|
+
/** What a read of a repository answered, or the refusal the host made. */
|
|
66
|
+
export type Read<T> = ({ ok: true } & T) | { ok: false; status: number; message: string }
|
|
67
|
+
|
|
68
|
+
/** One repository's state, as the host sees it. */
|
|
69
|
+
export interface StatusFacts {
|
|
70
|
+
/** Anything has ever been pushed to this name. */
|
|
71
|
+
exists: boolean
|
|
72
|
+
/** It holds a Signer List, so a stranger's push is refused (docs/adr/0012). */
|
|
73
|
+
claimed: boolean
|
|
74
|
+
/** It holds a Reader List, so a stranger's read is refused (docs/adr/0013). */
|
|
75
|
+
private: boolean
|
|
76
|
+
/** Ref name → sha, as the Index holds it. */
|
|
77
|
+
refs: Record<string, string>
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Who moved each ref, as the host recorded it (docs/adr/0011). */
|
|
81
|
+
export type ProvenanceFacts = Record<string, { signer: string; ts: string }>
|
|
82
|
+
|
|
83
|
+
/** What a watch saw: a ref that moved, or the deadline. */
|
|
84
|
+
export type WatchOutcome = { timedOut: false; ref: string; sha: string | null } | { timedOut: true }
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Everything the tools touch that this module cannot compute.
|
|
88
|
+
*
|
|
89
|
+
* `status` and `provenance` return a `Read`, never throw, because a refusal is
|
|
90
|
+
* an ANSWER the host made and has to survive the trip verbatim — turning a 401
|
|
91
|
+
* into an exception here is how a refusal becomes "something went wrong".
|
|
92
|
+
* `watch` may throw: an event stream that cannot be reached is not a verdict
|
|
93
|
+
* about the repository, and reporting it as one would be a lie.
|
|
94
|
+
*/
|
|
95
|
+
export interface McpDeps {
|
|
96
|
+
/** Reported in the handshake, so a client can name what it is talking to. */
|
|
97
|
+
version: string
|
|
98
|
+
/** This deployment's hostname, for the manual and for naming it in an error. */
|
|
99
|
+
host: string
|
|
100
|
+
/** What this deployment offers (`shared/capabilities.ts`). */
|
|
101
|
+
caps: Capabilities
|
|
102
|
+
/** Who runs it (`shared/operator.ts`), or nobody. */
|
|
103
|
+
operator: Operator | null
|
|
104
|
+
status(name: string): Promise<Read<StatusFacts>>
|
|
105
|
+
provenance(name: string): Promise<Read<{ repo: string; provenance: ProvenanceFacts }>>
|
|
106
|
+
watch(name: string, ref: string | null, timeoutMs: number): Promise<WatchOutcome>
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface ToolResult {
|
|
110
|
+
content: { type: 'text'; text: string }[]
|
|
111
|
+
isError?: boolean
|
|
112
|
+
[key: string]: unknown
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const json = (value: unknown): ToolResult => ({
|
|
116
|
+
content: [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
const refuse = (message: string): ToolResult => ({
|
|
120
|
+
content: [{ type: 'text', text: message }],
|
|
121
|
+
isError: true,
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The name grammar, applied before the host is asked.
|
|
126
|
+
*
|
|
127
|
+
* The same `REPO_ID` every other entry point applies (`src/repo.ts`,
|
|
128
|
+
* `shared/events.ts`): a name one surface accepts and another rejects is a
|
|
129
|
+
* repository half the service can see. Refused here rather than forwarded so a
|
|
130
|
+
* path-shaped name never becomes a request at all.
|
|
131
|
+
*/
|
|
132
|
+
function badName(name: string): string | null {
|
|
133
|
+
return REPO_ID.test(name)
|
|
134
|
+
? null
|
|
135
|
+
: `walgit: "${name}" is not a repository name here — one flat segment of letters, digits, dot, dash or underscore, starting with a letter or a digit.`
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The MCP server this host serves, wired over `deps`.
|
|
140
|
+
*
|
|
141
|
+
* Returned unconnected: the transport is the caller's, which is what lets one
|
|
142
|
+
* function serve a Streamable HTTP request in the Worker and an in-memory pair
|
|
143
|
+
* in a test. The descriptions are written for the model that reads the tool
|
|
144
|
+
* list and nothing else — that list is the only documentation an MCP client
|
|
145
|
+
* sees before it calls something.
|
|
146
|
+
*/
|
|
147
|
+
export function createAgentgitMcp(deps: McpDeps): McpServer {
|
|
148
|
+
const server = new McpServer({ name: 'agentgit', version: deps.version })
|
|
149
|
+
|
|
150
|
+
const name = z
|
|
151
|
+
.string()
|
|
152
|
+
.describe('The repository name — the `<name>` in `https://host/<name>.git`.')
|
|
153
|
+
|
|
154
|
+
server.registerTool(
|
|
155
|
+
'agentgit_status',
|
|
156
|
+
{
|
|
157
|
+
description:
|
|
158
|
+
"What the host knows about a repository name: whether anything has been pushed to it, whether it holds a Signer List (claimed, so a stranger cannot push), whether it holds a Reader List (private, so a stranger cannot read), and every ref with its sha. Reads only; creates nothing. A free name answers exists: false rather than an error, so this is how you check before claiming one. signedPushes is the deployment's, not this name's: it says whether a push to anything here can be signed at all.",
|
|
159
|
+
inputSchema: { name },
|
|
160
|
+
},
|
|
161
|
+
async (input): Promise<ToolResult> => {
|
|
162
|
+
const bad = badName(input.name)
|
|
163
|
+
if (bad) return refuse(bad)
|
|
164
|
+
const read = await deps.status(input.name)
|
|
165
|
+
if (!read.ok) return refuse(read.message)
|
|
166
|
+
return json({
|
|
167
|
+
name: input.name,
|
|
168
|
+
exists: read.exists,
|
|
169
|
+
claimed: read.claimed,
|
|
170
|
+
private: read.private,
|
|
171
|
+
// An array rather than the map the Index holds: a tool result is read
|
|
172
|
+
// by a model, and a list of {ref, sha} survives truncation in a way an
|
|
173
|
+
// object whose KEYS are the interesting part does not.
|
|
174
|
+
refs: Object.entries(read.refs).map(([ref, sha]) => ({ ref, sha })),
|
|
175
|
+
signedPushes: deps.caps.signedPushes,
|
|
176
|
+
})
|
|
177
|
+
},
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
server.registerTool(
|
|
181
|
+
'agentgit_watch',
|
|
182
|
+
{
|
|
183
|
+
description:
|
|
184
|
+
'Block until a ref in a repository moves, then say what it is now. This is the handoff primitive: call it to wait for the other agent to push. Answers { ref, sha } when one moves, or { timedOut: true } when none did before the deadline — which is an answer, not a failure, so call it again to keep waiting. It touches no clone: fetching what it reports is yours to do.',
|
|
185
|
+
inputSchema: {
|
|
186
|
+
name,
|
|
187
|
+
ref: z
|
|
188
|
+
.string()
|
|
189
|
+
.optional()
|
|
190
|
+
.describe('A full ref name, e.g. refs/heads/main. Omit to watch every ref.'),
|
|
191
|
+
timeoutMs: z
|
|
192
|
+
.number()
|
|
193
|
+
.int()
|
|
194
|
+
// Positive, so a `0` or a negative does not become a watch that
|
|
195
|
+
// answers `{ timedOut: true }` before the socket is even open —
|
|
196
|
+
// which reads as "nothing moved" and is a claim about the repository
|
|
197
|
+
// rather than about the argument.
|
|
198
|
+
.positive()
|
|
199
|
+
.optional()
|
|
200
|
+
.describe(`How long to wait, capped at ${MAX_WATCH_MS}ms by the host.`),
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
async (input): Promise<ToolResult> => {
|
|
204
|
+
const bad = badName(input.name)
|
|
205
|
+
if (bad) return refuse(bad)
|
|
206
|
+
const ref = input.ref ?? null
|
|
207
|
+
if (ref !== null && !REF_NAME.test(ref)) {
|
|
208
|
+
return refuse(`walgit: "${ref}" is not a full ref name — refs/heads/main, not main.`)
|
|
209
|
+
}
|
|
210
|
+
// The host's cap, not the caller's (see `MAX_WATCH_MS`).
|
|
211
|
+
const timeoutMs = Math.min(input.timeoutMs ?? MAX_WATCH_MS, MAX_WATCH_MS)
|
|
212
|
+
let outcome: WatchOutcome
|
|
213
|
+
try {
|
|
214
|
+
outcome = await deps.watch(input.name, ref, timeoutMs)
|
|
215
|
+
} catch (error) {
|
|
216
|
+
// Named rather than hung, and the HOST is named: a watch that cannot
|
|
217
|
+
// reach the event stream is a fact about this deployment, and a client
|
|
218
|
+
// told only "failed" has nothing to retry against.
|
|
219
|
+
return refuse(
|
|
220
|
+
`walgit: could not watch ${input.name} on ${deps.host}: ${
|
|
221
|
+
error instanceof Error ? error.message : String(error)
|
|
222
|
+
}`,
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
return json({
|
|
226
|
+
timedOut: outcome.timedOut,
|
|
227
|
+
repo: input.name,
|
|
228
|
+
// Spelled out rather than left off, because shape alone is ambiguous: a
|
|
229
|
+
// deleted ref carries no sha, and `{ sha: null }` on its own reads as a
|
|
230
|
+
// handoff that landed.
|
|
231
|
+
ref: outcome.timedOut ? null : outcome.ref,
|
|
232
|
+
sha: outcome.timedOut ? null : outcome.sha,
|
|
233
|
+
})
|
|
234
|
+
},
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
server.registerTool(
|
|
238
|
+
'agentgit_provenance',
|
|
239
|
+
{
|
|
240
|
+
description:
|
|
241
|
+
'Who pushed a ref: the SSH key fingerprint that signed the push, and when it landed. A key, never a user — there are no accounts here. A ref nobody signed answers signer: null, which is the ordinary answer, because signing is opt-in.',
|
|
242
|
+
inputSchema: {
|
|
243
|
+
name,
|
|
244
|
+
ref: z.string().describe('A full ref name, e.g. refs/heads/main.'),
|
|
245
|
+
},
|
|
246
|
+
},
|
|
247
|
+
async (input): Promise<ToolResult> => {
|
|
248
|
+
const bad = badName(input.name)
|
|
249
|
+
if (bad) return refuse(bad)
|
|
250
|
+
const read = await deps.provenance(input.name)
|
|
251
|
+
if (!read.ok) return refuse(read.message)
|
|
252
|
+
const entry = read.provenance[input.ref]
|
|
253
|
+
return json({
|
|
254
|
+
repo: input.name,
|
|
255
|
+
ref: input.ref,
|
|
256
|
+
signer: entry?.signer ?? null,
|
|
257
|
+
ts: entry?.ts ?? null,
|
|
258
|
+
})
|
|
259
|
+
},
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
server.registerResource(
|
|
263
|
+
'manual',
|
|
264
|
+
MANUAL_URI,
|
|
265
|
+
{
|
|
266
|
+
title: 'agentgit manual',
|
|
267
|
+
description:
|
|
268
|
+
"This host's own /llms.txt — push-to-create, claiming a name, Reader Lists, Proposals and the event stream, with every limit this deployment actually enforces.",
|
|
269
|
+
mimeType: 'text/markdown',
|
|
270
|
+
},
|
|
271
|
+
async (uri) => ({
|
|
272
|
+
contents: [
|
|
273
|
+
{
|
|
274
|
+
uri: uri.href,
|
|
275
|
+
mimeType: 'text/markdown',
|
|
276
|
+
// The same renderer the `/llms.txt` route calls, over the same
|
|
277
|
+
// capabilities: one document, two ways to it, and no second copy to
|
|
278
|
+
// promise a limit this deployment does not have.
|
|
279
|
+
text: renderLlms(deps.host, deps.caps, deps.operator),
|
|
280
|
+
},
|
|
281
|
+
],
|
|
282
|
+
}),
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
return server
|
|
286
|
+
}
|
|
@@ -146,6 +146,26 @@ export const READ_CHALLENGE_SCHEME = 'walgit-ssh'
|
|
|
146
146
|
/** Where a subscriber connects. A WebSocket upgrade, and nothing else. */
|
|
147
147
|
export const EVENTS_PATH = '/_walgit/events'
|
|
148
148
|
|
|
149
|
+
/**
|
|
150
|
+
* The Model Context Protocol endpoint (Streamable HTTP), answered at the edge.
|
|
151
|
+
*
|
|
152
|
+
* An MCP client reaches walgit by URL, so there is nothing to install and
|
|
153
|
+
* nothing to spawn — which is the whole reason it is here rather than in a
|
|
154
|
+
* package an agent's harness has to start. It carries only what the host can
|
|
155
|
+
* answer without the agent's disk: a name's state, a ref moving, who pushed it,
|
|
156
|
+
* and the manual. Everything that touches a clone stays a shell command.
|
|
157
|
+
*
|
|
158
|
+
* Under `/_walgit/` like health, events and provenance, and for the same
|
|
159
|
+
* reason: the prefix is reserved, and a repository is reached at
|
|
160
|
+
* `/<name>.git/…`, so this route cannot shadow one — not even a repository
|
|
161
|
+
* actually called `mcp`, which lives at `/mcp.git/…`.
|
|
162
|
+
*
|
|
163
|
+
* Both verbs, on one path: Streamable HTTP puts client messages on POST and the
|
|
164
|
+
* server-to-client stream on GET, and a transport that claimed only one of them
|
|
165
|
+
* is a client that connects and then hears nothing.
|
|
166
|
+
*/
|
|
167
|
+
export const MCP_PATH = '/_walgit/mcp'
|
|
168
|
+
|
|
149
169
|
/**
|
|
150
170
|
* Where the container publishes a push it has already made durable.
|
|
151
171
|
*
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
|
|
26
26
|
import {
|
|
27
27
|
HEALTH_PATH,
|
|
28
|
+
MCP_PATH,
|
|
28
29
|
PROVENANCE_PATH,
|
|
29
30
|
REJECT_HEADER,
|
|
30
31
|
REPO_ID,
|
|
@@ -72,6 +73,13 @@ export type RequestKind =
|
|
|
72
73
|
// demand for the feature and any refusal it produces, and would lose the
|
|
73
74
|
// repository name with them.
|
|
74
75
|
| 'provenance'
|
|
76
|
+
// An MCP client calling a tool (`shared/mcp.ts`), answered at the edge like
|
|
77
|
+
// the documents above. Its own kind rather than `other` for the reason
|
|
78
|
+
// `provenance` is, and one kind for the whole endpoint rather than one per
|
|
79
|
+
// tool: the tool and the repository it names are inside a JSON-RPC body, and
|
|
80
|
+
// a classifier that read request bodies to label a row would be buffering
|
|
81
|
+
// every push to count it.
|
|
82
|
+
| 'mcp'
|
|
75
83
|
| 'other'
|
|
76
84
|
|
|
77
85
|
export type Outcome = 'ok' | 'reject'
|
|
@@ -143,6 +151,9 @@ export function otherBucket(pathname: string): OtherBucket {
|
|
|
143
151
|
*/
|
|
144
152
|
export function classifyRequest(method: string, pathname: string, search: string): RequestFacts {
|
|
145
153
|
if (pathname === HEALTH_PATH) return { kind: 'health', repo: '' }
|
|
154
|
+
// No repository: the name a tool acts on travels in the JSON-RPC body, and
|
|
155
|
+
// the body is not something this function reads (see `RequestKind`).
|
|
156
|
+
if (pathname === MCP_PATH) return { kind: 'mcp', repo: '' }
|
|
146
157
|
if (pathname === '/' && (method === 'GET' || method === 'HEAD')) {
|
|
147
158
|
return { kind: 'instructions', repo: '' }
|
|
148
159
|
}
|
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
EXPIRE_PATH,
|
|
53
53
|
INTERNAL_HEADER,
|
|
54
54
|
INTERNAL_HEADERS,
|
|
55
|
+
MCP_PATH,
|
|
55
56
|
SERVED_HEADER,
|
|
56
57
|
} from '../shared/protocol'
|
|
57
58
|
import {
|
|
@@ -61,6 +62,7 @@ import {
|
|
|
61
62
|
type RequestMetric,
|
|
62
63
|
} from '../shared/telemetry'
|
|
63
64
|
import { BROADCAST_PATH, EVENTS_OBJECT_NAME, WalgitEvents } from './events-do'
|
|
65
|
+
import { handleMcp } from './mcp'
|
|
64
66
|
// The card's picture, as bytes in the bundle (wrangler.jsonc's `Data` rule).
|
|
65
67
|
// Rendered once by `scripts/render-og-image.ts` in the zbc repository and
|
|
66
68
|
// committed — never drawn per request.
|
|
@@ -535,6 +537,50 @@ export default {
|
|
|
535
537
|
return events(request, url, env, caps)
|
|
536
538
|
}
|
|
537
539
|
|
|
540
|
+
// The MCP endpoint (`shared/mcp.ts`), answered at the edge like the two
|
|
541
|
+
// documents above: a tool call is a question about a name, and the manual
|
|
542
|
+
// it also serves is rendered from these same capabilities rather than
|
|
543
|
+
// fetched. Unconditionally routed, unlike the socket above — the endpoint
|
|
544
|
+
// is a read surface that exists on every deployment, and the one tool that
|
|
545
|
+
// needs the stream (`agentgit_watch`) says so itself where it is off.
|
|
546
|
+
//
|
|
547
|
+
// Same collision argument as `/llms.txt` and its neighbours, and stronger:
|
|
548
|
+
// `/_walgit/` is reserved, and a repository called `mcp` is reached at
|
|
549
|
+
// `/mcp.git/…`, so this route cannot shadow one.
|
|
550
|
+
if (url.pathname === MCP_PATH) {
|
|
551
|
+
const response = await handleMcp(request, env, caps, operator, url.host)
|
|
552
|
+
record(env, ctx, {
|
|
553
|
+
// Classified rather than hand-labelled, so the kind this row carries
|
|
554
|
+
// and the kind `shared/telemetry.ts` names for this path cannot become
|
|
555
|
+
// two facts.
|
|
556
|
+
...classifyRequest(request.method, url.pathname, url.search),
|
|
557
|
+
// From the HTTP status, and deliberately not from the JSON-RPC body:
|
|
558
|
+
// a tool that REFUSED — a Private name an unproven reader asked about —
|
|
559
|
+
// answers 200 carrying `isError`, and is counted `ok` here. That is the
|
|
560
|
+
// honest reading of this column (the request was served) and the only
|
|
561
|
+
// affordable one: seeing the refusal would mean buffering and parsing
|
|
562
|
+
// every response body to label a row. A refusal the endpoint makes at
|
|
563
|
+
// the HTTP level, a malformed JSON-RPC body's 400, is counted.
|
|
564
|
+
outcome: response.ok ? 'ok' : 'reject',
|
|
565
|
+
reject: response.ok ? '' : 'other',
|
|
566
|
+
status: response.status,
|
|
567
|
+
// The container answers `agentgit_status` and `agentgit_provenance`
|
|
568
|
+
// behind this, but the REQUEST was answered here — `served` is about
|
|
569
|
+
// which layer produced the response, and saying otherwise would make
|
|
570
|
+
// the `edge` refusal signal unreadable.
|
|
571
|
+
served: false,
|
|
572
|
+
cold: false,
|
|
573
|
+
ttfbMs: Date.now() - startedAt,
|
|
574
|
+
totalMs: Date.now() - startedAt,
|
|
575
|
+
// Not counted: an MCP body is small and may be a stream held open for
|
|
576
|
+
// five minutes by `agentgit_watch`, and wrapping it to weigh it would
|
|
577
|
+
// hold the datapoint for the length of the wait.
|
|
578
|
+
bytesServed: 0,
|
|
579
|
+
bytesReceived: Number(request.headers.get('content-length') ?? '0') || 0,
|
|
580
|
+
})
|
|
581
|
+
return response
|
|
582
|
+
}
|
|
583
|
+
|
|
538
584
|
const facts = classifyRequest(request.method, url.pathname, url.search)
|
|
539
585
|
|
|
540
586
|
// The container's expiry endpoint trusts INTERNAL_HEADER to mean "the
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MCP endpoint's Workers half: a transport, and the three reads.
|
|
3
|
+
*
|
|
4
|
+
* Everything an agent can ASK is `shared/mcp.ts` — the tools, their schemas,
|
|
5
|
+
* their descriptions and the one rule about refusals — and it is tested there
|
|
6
|
+
* against a real MCP client with no runtime. What is left here is exactly the
|
|
7
|
+
* part that needs one: a Streamable HTTP transport, a container round trip, and
|
|
8
|
+
* a socket to the ref-event Durable Object.
|
|
9
|
+
*
|
|
10
|
+
* Two properties this file is responsible for keeping:
|
|
11
|
+
*
|
|
12
|
+
* - **The gate is the host's own, not a second copy.** `status` and
|
|
13
|
+
* `provenance` both go through the container's `PROVENANCE_PATH`, which is
|
|
14
|
+
* already placed behind exactly the credential a clone needs and already
|
|
15
|
+
* applies the Read Challenge for a Private name (`src/http.ts`,
|
|
16
|
+
* docs/adr/0013). A refusal it makes is forwarded verbatim; the internal
|
|
17
|
+
* `REFS_PATH` read that fills in the refs happens ONLY after that refusal
|
|
18
|
+
* did not come, because it is `INTERNAL_HEADER`-gated and gates nothing
|
|
19
|
+
* itself.
|
|
20
|
+
* - **The request is served at the edge**, in the sense that matters: the MCP
|
|
21
|
+
* protocol itself is answered here and the container never routes
|
|
22
|
+
* `/_walgit/mcp`. `watch` subscribes to the Durable Object the way a
|
|
23
|
+
* WebSocket client does, and the manual is rendered from the same
|
|
24
|
+
* capabilities the `/llms.txt` route uses, so neither touches the container
|
|
25
|
+
* at all.
|
|
26
|
+
*
|
|
27
|
+
* `status` and `provenance` DO wake it, and `status` twice — once for the gated
|
|
28
|
+
* provenance read and once for `REFS_PATH`. That is the price of the first
|
|
29
|
+
* property rather than an oversight: refs are authoritative in the Index
|
|
30
|
+
* (docs/adr/0007), the Index is reachable only with the container's object-store
|
|
31
|
+
* credentials (`shared/container-env.ts`), and the gate that decides whether
|
|
32
|
+
* this caller may see them is the container's too. An edge answer would need
|
|
33
|
+
* both a second verifier and a second reader — the two things ADR-0013 and
|
|
34
|
+
* ADR-0007 each refuse. Folding the refs into the provenance response would
|
|
35
|
+
* save the second trip and is a container-route change this one did not make.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { StreamableHTTPTransport } from '@hono/mcp'
|
|
39
|
+
import { getContainer } from '@cloudflare/containers'
|
|
40
|
+
import { Hono } from 'hono'
|
|
41
|
+
|
|
42
|
+
import type { Capabilities } from '../shared/capabilities'
|
|
43
|
+
import { parseTokens } from '../shared/credentials'
|
|
44
|
+
import { authorizeSubscribe } from '../shared/events'
|
|
45
|
+
import {
|
|
46
|
+
type McpDeps,
|
|
47
|
+
type ProvenanceFacts,
|
|
48
|
+
type Read,
|
|
49
|
+
type StatusFacts,
|
|
50
|
+
type WatchOutcome,
|
|
51
|
+
createAgentgitMcp,
|
|
52
|
+
} from '../shared/mcp'
|
|
53
|
+
import type { Operator } from '../shared/operator'
|
|
54
|
+
import {
|
|
55
|
+
EVENTS_PATH,
|
|
56
|
+
INTERNAL_HEADER,
|
|
57
|
+
MCP_PATH,
|
|
58
|
+
PROVENANCE_PATH,
|
|
59
|
+
REFS_PATH,
|
|
60
|
+
} from '../shared/protocol'
|
|
61
|
+
import { EVENTS_OBJECT_NAME } from './events-do'
|
|
62
|
+
import type { Env } from './index'
|
|
63
|
+
|
|
64
|
+
/** What a claimed name's provenance read carries about its lists. */
|
|
65
|
+
interface Claim {
|
|
66
|
+
signers: string[]
|
|
67
|
+
readers?: string[]
|
|
68
|
+
ts: string
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Answer one MCP request.
|
|
73
|
+
*
|
|
74
|
+
* A fresh `McpServer` per request, like the inbox's endpoint and for the same
|
|
75
|
+
* reason: a Workers isolate is per-request and holds no session, so there is no
|
|
76
|
+
* long-lived server to keep. `app.all` because Streamable HTTP puts client
|
|
77
|
+
* messages on POST and the server-to-client stream on GET, and a transport
|
|
78
|
+
* mounted for one of them is a client that connects and then hears nothing.
|
|
79
|
+
*/
|
|
80
|
+
export async function handleMcp(
|
|
81
|
+
request: Request,
|
|
82
|
+
env: Env,
|
|
83
|
+
caps: Capabilities,
|
|
84
|
+
operator: Operator | null,
|
|
85
|
+
host: string,
|
|
86
|
+
): Promise<Response> {
|
|
87
|
+
const server = createAgentgitMcp(deps(request, env, caps, operator, host))
|
|
88
|
+
const transport = new StreamableHTTPTransport()
|
|
89
|
+
await server.connect(transport)
|
|
90
|
+
const app = new Hono()
|
|
91
|
+
app.all(MCP_PATH, (c) => transport.handleRequest(c))
|
|
92
|
+
return app.fetch(request)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function deps(
|
|
96
|
+
request: Request,
|
|
97
|
+
env: Env,
|
|
98
|
+
caps: Capabilities,
|
|
99
|
+
operator: Operator | null,
|
|
100
|
+
host: string,
|
|
101
|
+
): McpDeps {
|
|
102
|
+
// The caller's own credential, forwarded unchanged to every gated read. An
|
|
103
|
+
// MCP client sends it as an ordinary Authorization header, which is the same
|
|
104
|
+
// header a clone of a Private repository presents.
|
|
105
|
+
const authorization = request.headers.get('authorization')
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
version: env.WALGIT_BUILD_ID ?? '0.0.0',
|
|
109
|
+
host,
|
|
110
|
+
caps,
|
|
111
|
+
operator,
|
|
112
|
+
|
|
113
|
+
async status(name): Promise<Read<StatusFacts>> {
|
|
114
|
+
const read = await provenanceRead(env, authorization, name)
|
|
115
|
+
if (!read.ok) return read
|
|
116
|
+
// Only now: `REFS_PATH` is internal and judges nothing, so reading it
|
|
117
|
+
// before the gate above answered would be the second copy of the gate
|
|
118
|
+
// this file exists not to have.
|
|
119
|
+
const refs = await readRefs(env, name)
|
|
120
|
+
const claim = read.claim
|
|
121
|
+
return {
|
|
122
|
+
ok: true,
|
|
123
|
+
// The same judgment `src/http.ts` makes of a name nobody has pushed to:
|
|
124
|
+
// a repository with no refs is one that does not exist yet.
|
|
125
|
+
exists: Object.keys(refs).length > 0,
|
|
126
|
+
claimed: claim !== undefined,
|
|
127
|
+
// Presence is the switch, and `[]` is a value — an empty Reader List
|
|
128
|
+
// means the Signer List reads this and nobody else (docs/adr/0013).
|
|
129
|
+
private: claim?.readers !== undefined,
|
|
130
|
+
refs,
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
async provenance(name): Promise<Read<{ repo: string; provenance: ProvenanceFacts }>> {
|
|
135
|
+
const read = await provenanceRead(env, authorization, name)
|
|
136
|
+
if (!read.ok) return read
|
|
137
|
+
return { ok: true, repo: name, provenance: read.provenance }
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
watch: (name, ref, timeoutMs) => watchRef(env, caps, authorization, name, ref, timeoutMs),
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* One repository's provenance and Claim, through the container's own gate.
|
|
146
|
+
*
|
|
147
|
+
* The status code is carried out with the body, because the body is the
|
|
148
|
+
* refusal the host wrote and `shared/mcp.ts` forwards it verbatim — a 401 for a
|
|
149
|
+
* Private name an unproven reader asked about has to reach the agent saying
|
|
150
|
+
* what `info/refs` would say, and nothing more.
|
|
151
|
+
*/
|
|
152
|
+
async function provenanceRead(
|
|
153
|
+
env: Env,
|
|
154
|
+
authorization: string | null,
|
|
155
|
+
name: string,
|
|
156
|
+
): Promise<Read<{ provenance: ProvenanceFacts; claim?: Claim }>> {
|
|
157
|
+
const headers = new Headers()
|
|
158
|
+
if (authorization) headers.set('authorization', authorization)
|
|
159
|
+
const response = await getContainer(env.WALGIT_CONTAINER).fetch(
|
|
160
|
+
new Request(`https://walgit.internal${PROVENANCE_PATH}?repo=${encodeURIComponent(name)}`, {
|
|
161
|
+
headers,
|
|
162
|
+
}),
|
|
163
|
+
)
|
|
164
|
+
if (!response.ok) {
|
|
165
|
+
const message = (await response.text()).trim()
|
|
166
|
+
return {
|
|
167
|
+
ok: false,
|
|
168
|
+
status: response.status,
|
|
169
|
+
message: message === '' ? `walgit: the host answered ${response.status}` : message,
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const body = (await response.json()) as { provenance?: ProvenanceFacts; claim?: Claim }
|
|
173
|
+
return { ok: true, provenance: body.provenance ?? {}, claim: body.claim }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** One repository's ref state, read from the Index through the container. */
|
|
177
|
+
async function readRefs(env: Env, name: string): Promise<Record<string, string>> {
|
|
178
|
+
const response = await getContainer(env.WALGIT_CONTAINER).fetch(
|
|
179
|
+
new Request(`https://walgit.internal${REFS_PATH}?repo=${encodeURIComponent(name)}`, {
|
|
180
|
+
headers: { [INTERNAL_HEADER]: '1' },
|
|
181
|
+
}),
|
|
182
|
+
)
|
|
183
|
+
// Empty rather than thrown: the gate above already said this name may be
|
|
184
|
+
// read, and a refs lookup that did not answer is a repository with nothing
|
|
185
|
+
// known about it — which is what `exists: false` says.
|
|
186
|
+
if (!response.ok) return {}
|
|
187
|
+
const body = (await response.json()) as { refs?: Record<string, string> }
|
|
188
|
+
return body.refs ?? {}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Wait for one ref to move, over the same socket a `watch` client uses.
|
|
193
|
+
*
|
|
194
|
+
* The gate is the event stream's own, in both halves: the deployment
|
|
195
|
+
* credential is checked here exactly as `events()` checks it in `index.ts`, and
|
|
196
|
+
* the Reader List is checked by the Durable Object against the credential this
|
|
197
|
+
* request forwards (`worker/events-do.ts`). Neither is re-decided.
|
|
198
|
+
*
|
|
199
|
+
* Throws rather than returning a verdict when the stream cannot be reached or
|
|
200
|
+
* refuses: an answer of `{ timedOut: true }` would tell an agent that nothing
|
|
201
|
+
* happened, which is a different and false statement.
|
|
202
|
+
*/
|
|
203
|
+
async function watchRef(
|
|
204
|
+
env: Env,
|
|
205
|
+
caps: Capabilities,
|
|
206
|
+
authorization: string | null,
|
|
207
|
+
repo: string,
|
|
208
|
+
ref: string | null,
|
|
209
|
+
timeoutMs: number,
|
|
210
|
+
): Promise<WatchOutcome> {
|
|
211
|
+
if (!caps.events) {
|
|
212
|
+
throw new Error('this deployment does not serve the ref-event stream')
|
|
213
|
+
}
|
|
214
|
+
if (
|
|
215
|
+
!authorizeSubscribe({
|
|
216
|
+
authorization,
|
|
217
|
+
tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
|
|
218
|
+
isPublic: caps.publicAccess,
|
|
219
|
+
})
|
|
220
|
+
) {
|
|
221
|
+
throw new Error('unauthorized')
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const headers = new Headers({ upgrade: 'websocket' })
|
|
225
|
+
if (authorization) headers.set('authorization', authorization)
|
|
226
|
+
const stub = env.WALGIT_EVENTS.get(env.WALGIT_EVENTS.idFromName(EVENTS_OBJECT_NAME))
|
|
227
|
+
const response = await stub.fetch(
|
|
228
|
+
new Request(`https://walgit.internal${EVENTS_PATH}`, { headers }),
|
|
229
|
+
)
|
|
230
|
+
const socket = response.webSocket
|
|
231
|
+
if (!socket) throw new Error(`the event stream answered ${response.status}`)
|
|
232
|
+
socket.accept()
|
|
233
|
+
|
|
234
|
+
return new Promise<WatchOutcome>((resolve, reject) => {
|
|
235
|
+
let settled = false
|
|
236
|
+
const finish = (run: () => void) => {
|
|
237
|
+
if (settled) return
|
|
238
|
+
settled = true
|
|
239
|
+
clearTimeout(timer)
|
|
240
|
+
try {
|
|
241
|
+
socket.close(1000, 'walgit: done')
|
|
242
|
+
} catch {
|
|
243
|
+
// Already gone.
|
|
244
|
+
}
|
|
245
|
+
run()
|
|
246
|
+
}
|
|
247
|
+
const timer = setTimeout(() => finish(() => resolve({ timedOut: true })), timeoutMs)
|
|
248
|
+
|
|
249
|
+
socket.addEventListener('message', (event) => {
|
|
250
|
+
let message: Record<string, unknown>
|
|
251
|
+
try {
|
|
252
|
+
const raw = typeof event.data === 'string' ? event.data : ''
|
|
253
|
+
message = JSON.parse(raw) as Record<string, unknown>
|
|
254
|
+
} catch {
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
if (typeof message.error === 'string') {
|
|
258
|
+
const error = message.error
|
|
259
|
+
finish(() => reject(new Error(error)))
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
// The handshake is current state for what was named, not a ref that
|
|
263
|
+
// moved — resolving on it would make every call return immediately.
|
|
264
|
+
if (message.ok === true) return
|
|
265
|
+
if (typeof message.ref !== 'string') return
|
|
266
|
+
const moved = message.ref
|
|
267
|
+
const sha = typeof message.sha === 'string' ? message.sha : null
|
|
268
|
+
finish(() => resolve({ timedOut: false, ref: moved, sha }))
|
|
269
|
+
})
|
|
270
|
+
socket.addEventListener('close', () =>
|
|
271
|
+
finish(() => reject(new Error('the event stream closed the subscription'))),
|
|
272
|
+
)
|
|
273
|
+
socket.addEventListener('error', () =>
|
|
274
|
+
finish(() => reject(new Error('the event stream failed'))),
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
// Omitting `refs` watches every ref in the repository, which is what a
|
|
278
|
+
// caller that named none asked for.
|
|
279
|
+
socket.send(JSON.stringify({ watch: [{ repo, ...(ref === null ? {} : { refs: [ref] }) }] }))
|
|
280
|
+
})
|
|
281
|
+
}
|