@fungi.computer/oyster 0.10.0 → 0.11.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.
Files changed (63) hide show
  1. package/README.md +33 -2
  2. package/dist/agents.d.ts +66 -22
  3. package/dist/agents.js +128 -38
  4. package/dist/authorization.d.ts +25 -3
  5. package/dist/authorization.js +47 -14
  6. package/dist/browser/capability-source.d.ts +23 -5
  7. package/dist/browser/capability-source.js +19 -22
  8. package/dist/browser/index.d.ts +2 -1
  9. package/dist/browser/index.js +1 -0
  10. package/dist/browser/live-view.d.ts +38 -0
  11. package/dist/browser/live-view.js +179 -0
  12. package/dist/channels/binding.d.ts +2 -0
  13. package/dist/channels/run-decision.d.ts +33 -0
  14. package/dist/channels/run-decision.js +25 -0
  15. package/dist/channels/visitor-channel.d.ts +84 -14
  16. package/dist/channels/visitor-channel.js +55 -32
  17. package/dist/channels/visitor-edge.d.ts +18 -2
  18. package/dist/channels/visitor-edge.js +67 -5
  19. package/dist/channels/visitors.d.ts +4 -0
  20. package/dist/channels/visitors.js +22 -1
  21. package/dist/channels/web-binding.d.ts +117 -0
  22. package/dist/channels/web-binding.js +227 -0
  23. package/dist/embed-metafiles.d.ts +8 -0
  24. package/dist/embed-metafiles.js +2 -0
  25. package/dist/embed-scripts.d.ts +8 -0
  26. package/dist/embed-scripts.js +3 -0
  27. package/dist/host.d.ts +3 -1
  28. package/dist/host.js +6 -1
  29. package/dist/page/embed-challenge.d.ts +19 -0
  30. package/dist/page/embed-challenge.js +45 -0
  31. package/dist/page/embed-error.d.ts +2 -0
  32. package/dist/page/embed-error.js +16 -0
  33. package/dist/page/embed-loader-protocol.d.ts +12 -0
  34. package/dist/page/embed-loader-protocol.js +29 -0
  35. package/dist/standalone/agent-connections.d.ts +22 -19
  36. package/dist/standalone/agent-connections.js +150 -106
  37. package/dist/standalone/agents.d.ts +168 -14
  38. package/dist/standalone/agents.js +310 -17
  39. package/dist/standalone/browser.d.ts +14 -2
  40. package/dist/standalone/browser.js +52 -4
  41. package/dist/standalone/channel-session-door.d.ts +4 -0
  42. package/dist/standalone/channel-session-door.js +72 -0
  43. package/dist/standalone/owner-routes.d.ts +4 -3
  44. package/dist/standalone/owner-routes.js +7 -1
  45. package/dist/standalone/visitor-edge.d.ts +36 -0
  46. package/dist/standalone/visitor-edge.js +67 -0
  47. package/dist/standalone/visitor-proof.d.ts +23 -0
  48. package/dist/standalone/visitor-proof.js +67 -0
  49. package/dist/standalone/website-channels.d.ts +134 -0
  50. package/dist/standalone/website-channels.js +262 -0
  51. package/dist/standalone/worker-routes.d.ts +4 -1
  52. package/dist/standalone/worker-routes.js +3 -0
  53. package/dist/standalone/worker.d.ts +2 -1
  54. package/dist/standalone/worker.js +4 -0
  55. package/dist/testing/capabilities.d.ts +3 -0
  56. package/dist/testing/capabilities.js +1 -0
  57. package/dist/testing/installation.d.ts +4 -2
  58. package/dist/testing/installation.js +7 -2
  59. package/dist/workers-git.js +2 -2
  60. package/docs/api/agents.md +103 -36
  61. package/docs/api/browser.md +115 -8
  62. package/docs/api/workers-git.md +6 -6
  63. package/package.json +31 -6
package/dist/host.d.ts CHANGED
@@ -16,7 +16,7 @@ export type { GuestLimits } from "./guest-policy.js";
16
16
  import { type TimingVariables } from "hono/timing";
17
17
  import * as Schema from "effect/Schema";
18
18
  import { type BackgroundSyncRefusal } from "@fungi.computer/puffball/background-replay";
19
- import { type Installation, type InstallationReader } from "./apps/installation.js";
19
+ import { type ApprovedGrant, type Installation, type InstallationReader } from "./apps/installation.js";
20
20
  import { type ResourceOption } from "./apps/permissions.js";
21
21
  import type { AppToolPolicy } from "./apps/tools.js";
22
22
  import type { LiveOysterKey } from "./keys.js";
@@ -144,6 +144,8 @@ export type CapabilityAdmission = Readonly<{
144
144
  principal: TenantPrincipal;
145
145
  /** The enabled installation the gate admitted for this capability. */
146
146
  installation: Installation;
147
+ /** The installation's approved grant for this capability: its operations and selected resources. */
148
+ grant: ApprovedGrant;
147
149
  }>;
148
150
  /** Capability routes read the host's admission from `c.env`; they never authenticate. */
149
151
  export type CapabilityEnv = {
package/dist/host.js CHANGED
@@ -492,8 +492,13 @@ export function oysterRouteTable(host) {
492
492
  : "write",
493
493
  }).kind === "refused")
494
494
  continue;
495
+ // The route names its exact resource; the table decides it within this
496
+ // grant's selection, never the principal's wider reach alone.
497
+ const grant = grantsFor(facts.installation, facts.declaration, facts.declaredOperations, capability.permission);
498
+ if (grant === null)
499
+ continue;
495
500
  url.pathname = `/${url.pathname.slice(capability.base.length)}`;
496
- return capabilityTable(capability).fetch(new Request(url, context.req.raw), { principal, installation });
501
+ return capabilityTable(capability).fetch(new Request(url, context.req.raw), { principal, installation, grant });
497
502
  }
498
503
  return refusal(403, "Capability permission denied");
499
504
  };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The Turnstile check a site can require before it mints a visitor. The
3
+ * embed document carries the public site key only when the owner asked for the
4
+ * check and the host holds its keys; the token goes back with the first mint.
5
+ */
6
+ type Turnstile = {
7
+ render(container: HTMLElement, options: {
8
+ sitekey: string;
9
+ callback: (token: string) => void;
10
+ "error-callback": () => void;
11
+ }): string;
12
+ remove(widgetId: string): void;
13
+ };
14
+ declare global {
15
+ var turnstile: Turnstile | undefined;
16
+ }
17
+ /** Show the check over the chat until it passes, then hand back its token. */
18
+ export declare function requestChallenge(siteKey: string): Promise<string>;
19
+ export {};
@@ -0,0 +1,45 @@
1
+ const scriptUrl = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
2
+ function loadTurnstile() {
3
+ const loaded = globalThis.turnstile;
4
+ if (loaded !== undefined)
5
+ return Promise.resolve(loaded);
6
+ return new Promise((resolve, reject) => {
7
+ const script = document.createElement("script");
8
+ script.src = scriptUrl;
9
+ script.async = true;
10
+ script.addEventListener("load", () => {
11
+ const api = globalThis.turnstile;
12
+ if (api === undefined)
13
+ reject(new Error("turnstile_unavailable"));
14
+ else
15
+ resolve(api);
16
+ });
17
+ script.addEventListener("error", () => {
18
+ reject(new Error("turnstile_unavailable"));
19
+ });
20
+ document.head.append(script);
21
+ });
22
+ }
23
+ /** Show the check over the chat until it passes, then hand back its token. */
24
+ export async function requestChallenge(siteKey) {
25
+ const api = await loadTurnstile();
26
+ const surface = document.createElement("div");
27
+ surface.setAttribute("aria-label", "Security check");
28
+ surface.className =
29
+ "fixed inset-0 z-10 flex items-center justify-center bg-base-100";
30
+ document.body.append(surface);
31
+ try {
32
+ return await new Promise((resolve, reject) => {
33
+ api.render(surface, {
34
+ sitekey: siteKey,
35
+ callback: resolve,
36
+ "error-callback": () => {
37
+ reject(new Error("turnstile_failed"));
38
+ },
39
+ });
40
+ });
41
+ }
42
+ finally {
43
+ surface.remove();
44
+ }
45
+ }
@@ -0,0 +1,2 @@
1
+ /** Report a widget failure without writing exception messages or visitor data. */
2
+ export declare function reportEmbedCatchFailure(operation: string, cause: unknown): void;
@@ -0,0 +1,16 @@
1
+ function describeCause(cause, depth = 0) {
2
+ if (!(cause instanceof Error))
3
+ return { kind: "non-error" };
4
+ const description = { kind: "error" };
5
+ if (cause.cause !== undefined && depth < 3)
6
+ description.cause = describeCause(cause.cause, depth + 1);
7
+ return description;
8
+ }
9
+ /** Report a widget failure without writing exception messages or visitor data. */
10
+ export function reportEmbedCatchFailure(operation, cause) {
11
+ console.error(JSON.stringify({
12
+ event: "hub_catch_failure",
13
+ operation,
14
+ cause: describeCause(cause),
15
+ }));
16
+ }
@@ -0,0 +1,12 @@
1
+ import * as z from "zod";
2
+ /** The parent accepts this constant only from its own iframe and serving origin. */
3
+ export declare const CLOSE_MESSAGE = "fungi-embed:close";
4
+ /** Decode the snippet's presentation choice; absent means the visitor's OS. */
5
+ export declare function parseEmbedTheme(value: string | undefined): "auto" | "light" | "dark" | null;
6
+ declare const siteThemeSchema: z.ZodObject<{
7
+ accent: z.ZodNullable<z.ZodString>;
8
+ originAllowed: z.ZodBoolean;
9
+ }, z.core.$strict>;
10
+ /** Decode the bounded public accent, without taking host-page CSS or fonts. */
11
+ export declare function parseSiteTheme(body: string): z.infer<typeof siteThemeSchema> | null;
12
+ export {};
@@ -0,0 +1,29 @@
1
+ import * as Schema from "effect/Schema";
2
+ import * as Option from "effect/Option";
3
+ import * as z from "zod";
4
+ /** The parent accepts this constant only from its own iframe and serving origin. */
5
+ export const CLOSE_MESSAGE = "fungi-embed:close";
6
+ const embedThemeSchema = z.enum(["light", "dark", "auto"]).default("auto");
7
+ /** Decode the snippet's presentation choice; absent means the visitor's OS. */
8
+ export function parseEmbedTheme(value) {
9
+ const parsed = embedThemeSchema.safeParse(value);
10
+ return parsed.success ? parsed.data : null;
11
+ }
12
+ const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
13
+ const siteThemeSchema = z.strictObject({
14
+ accent: z
15
+ .string()
16
+ .regex(/^#[0-9a-f]{6}$/iu)
17
+ .nullable(),
18
+ originAllowed: z.boolean(),
19
+ });
20
+ /** Decode the bounded public accent, without taking host-page CSS or fonts. */
21
+ export function parseSiteTheme(body) {
22
+ if (body.length > 128)
23
+ return null;
24
+ const decoded = decodeJson(body);
25
+ if (Option.isNone(decoded))
26
+ return null;
27
+ const parsed = siteThemeSchema.safeParse(decoded.value);
28
+ return parsed.success ? parsed.data : null;
29
+ }
@@ -1,18 +1,6 @@
1
1
  import type { McpServersConnectionOptions } from "@fungi.computer/knapsack";
2
- import { createSealedCustody, type ConnectionProjection, type EgressRef, type SqlStore } from "@fungi.computer/veil/connections";
3
- import { type AgentMcpServer, type AgentMcpServerInput, type AgentMcpServerRefusal } from "../agents.js";
4
- /** One Agent MCP request as plain data, so it can cross the Durable Object RPC boundary. */
5
- export type McpRequestData = Readonly<{
6
- url: string;
7
- method: string;
8
- headers: readonly (readonly [string, string])[];
9
- body: ArrayBuffer | null;
10
- }>;
11
- /** A refusal crosses RPC as data: a stable code, never a message. */
12
- type McpFetchRefusal = Readonly<{
13
- error: string;
14
- }>;
15
- export declare function mcpRequestData(request: Request): Promise<McpRequestData>;
2
+ import { createSealedCustody, type ConnectionProjection, type EgressRef, type McpRefusal, type McpRequestData, type SqlStore } from "@fungi.computer/veil/connections";
3
+ import { type ConnectionAccess, type ConnectionAdded, type ConnectionInput, type ConnectionRefusal, type OysterConnection } from "../agents.js";
16
4
  /**
17
5
  * This instance's Agent MCP connections over Veil's connections core. The
18
6
  * owner holds every credential; an Agent receives a secret-free projection and
@@ -27,12 +15,28 @@ export declare function createAgentMcpConnections(options: {
27
15
  /** Told after a change so the Agent drops captured tools. */
28
16
  notify: (agentId: string) => Promise<void>;
29
17
  ownerId: string;
18
+ /** Where an authorization server returns the owner; shown to them to register their own app. */
19
+ callbackUrl: string;
30
20
  }): {
31
- servers: (agentId: string) => Promise<readonly AgentMcpServer[] | null>;
32
- add: (agentId: string, input: AgentMcpServerInput) => Promise<AgentMcpServer | AgentMcpServerRefusal>;
33
- remove: (agentId: string, serverId: string) => Promise<boolean>;
21
+ list: () => Promise<readonly OysterConnection[]>;
22
+ add: (input: ConnectionInput) => Promise<ConnectionAdded | ConnectionRefusal>;
23
+ grant: (connectionId: string, agentId: string, access: ConnectionAccess) => Promise<Readonly<{
24
+ ok: true;
25
+ }> | ConnectionRefusal>;
26
+ ungrant: (connectionId: string, agentId: string) => Promise<boolean>;
27
+ remove: (connectionId: string) => Promise<boolean>;
28
+ tools: (connectionId: string) => Promise<readonly string[] | ConnectionRefusal>;
29
+ complete: (query: {
30
+ state: string;
31
+ code: string;
32
+ iss: string | undefined;
33
+ }) => Promise<Readonly<{
34
+ ok: true;
35
+ }> | McpRefusal>;
34
36
  projection: (agentId: string) => Promise<ConnectionProjection>;
35
- fetch: (agentId: string, ref: EgressRef, data: McpRequestData) => Promise<Response | McpFetchRefusal>;
37
+ fetch: (agentId: string, ref: EgressRef, data: McpRequestData) => Promise<Response | Readonly<{
38
+ error: string;
39
+ }>>;
36
40
  };
37
41
  /**
38
42
  * The Agent half: Knapsack connects to each granted server through a fetch that
@@ -44,4 +48,3 @@ export declare function agentMcpSourceOptions(input: {
44
48
  onUnavailable: McpServersConnectionOptions["onUnavailable"];
45
49
  fetch: (ref: EgressRef, request: Request) => Promise<Response>;
46
50
  }): McpServersConnectionOptions;
47
- export {};
@@ -1,7 +1,7 @@
1
1
  import { defineIdFamily } from "@fungi.computer/cairn";
2
- import { ConnectionsError, createConnections, createSealedCustody, } from "@fungi.computer/veil/connections";
2
+ import { ConnectionsError, createConnections, createSealedCustody, answerMcpRequest, mcpAgentSource, } from "@fungi.computer/veil/connections";
3
3
  import * as Effect from "effect/Effect";
4
- import { maxAgentMcpServers, } from "../agents.js";
4
+ import { maxAgentConnections, } from "../agents.js";
5
5
  const ids = defineIdFamily({
6
6
  family: "oyster-connection",
7
7
  version: 1,
@@ -9,14 +9,6 @@ const ids = defineIdFamily({
9
9
  });
10
10
  /** The Oyster owner is the only actor that manages connections. */
11
11
  const owner = "owner";
12
- export async function mcpRequestData(request) {
13
- return {
14
- url: request.url,
15
- method: request.method,
16
- headers: [...request.headers],
17
- body: request.body === null ? null : await request.arrayBuffer(),
18
- };
19
- }
20
12
  /**
21
13
  * This instance's Agent MCP connections over Veil's connections core. The
22
14
  * owner holds every credential; an Agent receives a secret-free projection and
@@ -31,87 +23,153 @@ export function createAgentMcpConnections(options) {
31
23
  send: options.send,
32
24
  }),
33
25
  authorize: (actor) => actor === owner,
26
+ oauth: { callbackUrl: options.callbackUrl, fetch: options.send },
34
27
  clock: () => Date.now(),
35
28
  ids: () => ids.connection.generate(),
36
29
  });
37
30
  const run = (effect) => Effect.runPromise(effect);
38
31
  const projection = (agentId) => run(connections.projection(agentId));
39
- async function servers(agentId) {
40
- if (!options.hasAgent(agentId))
41
- return null;
42
- const [granted, listed] = await Promise.all([
43
- projection(agentId),
44
- run(connections.list(owner)),
45
- ]);
46
- return granted.connections.flatMap((connection) => connection.surface.kind === "mcp"
47
- ? [
32
+ const holdersOf = async (connectionId) => (await run(connections.list(owner))).flatMap((row) => row.connectionId === connectionId
33
+ ? row.grants.map((grant) => grant.agentId)
34
+ : []);
35
+ const toolsFor = (access) => access === "all"
36
+ ? "all"
37
+ : access === "read"
38
+ ? { effect: "read" }
39
+ : [...access];
40
+ /** Every live connection with the Agents that may use it. */
41
+ async function list() {
42
+ return (await run(connections.list(owner))).flatMap((row) => row.state === "revoked"
43
+ ? []
44
+ : [
48
45
  {
49
- serverId: connection.connectionId,
50
- name: connection.name,
51
- url: connection.surface.url,
52
- hasBearer: listed.find((row) => row.connectionId === connection.connectionId)?.credentialKind === "static",
46
+ connectionId: row.connectionId,
47
+ name: row.name,
48
+ label: row.label,
49
+ kind: row.surface.kind,
50
+ url: row.surface.url,
51
+ auth: row.credentialKind === "static"
52
+ ? "token"
53
+ : row.credentialKind === "oauth"
54
+ ? "oauth"
55
+ : "none",
56
+ state: row.state === "active" ? "connected" : row.state,
57
+ grants: row.grants.map((grant) => ({
58
+ agentId: grant.agentId,
59
+ access: grant.tools === "all"
60
+ ? "all"
61
+ : Array.isArray(grant.tools)
62
+ ? grant.tools
63
+ : "read",
64
+ })),
53
65
  },
54
- ]
55
- : []);
66
+ ]);
56
67
  }
57
- async function add(agentId, input) {
58
- const current = await servers(agentId);
59
- if (current === null)
60
- return { error: "not_found" };
68
+ /** Connect one MCP server. No Agent has it until the owner grants it. */
69
+ async function add(input) {
70
+ // Abandoned sign-ins age out before names are compared.
71
+ await run(connections.sweep());
61
72
  const url = new URL(input.url).href;
62
- if (current.some((server) => server.name === input.name || server.url === url))
63
- return { error: "duplicate_name" };
64
- if (current.length >= maxAgentMcpServers)
65
- return { error: "limit" };
66
73
  try {
67
- const draft = {
68
- requestId: ids.connection.generate(),
69
- name: input.name,
70
- surface: { kind: "mcp", url },
71
- };
72
- const { connectionId } = await run(input.bearer === null
73
- ? connections.begin(owner, { ...draft, credential: { kind: "none" } })
74
- : connections.begin(owner, {
75
- ...draft,
76
- credential: { kind: "static", placement: "bearer" },
77
- secret: input.bearer,
78
- }));
79
- await run(connections.grant(owner, { connectionId, agentId, tools: "all" }));
80
- await options.notify(agentId);
74
+ const requestId = ids.connection.generate();
75
+ const surface = { kind: "mcp", url };
76
+ const oauth = input.oauth;
77
+ const begun = await run(oauth !== undefined
78
+ ? connections.begin(owner, {
79
+ requestId,
80
+ name: input.name,
81
+ surface,
82
+ credential: {
83
+ kind: "oauth",
84
+ scope: oauth.scope,
85
+ clientId: oauth.clientId,
86
+ },
87
+ secret: oauth.clientSecret,
88
+ })
89
+ : input.bearer === null
90
+ ? connections.begin(owner, {
91
+ requestId,
92
+ name: input.name,
93
+ surface,
94
+ credential: { kind: "none" },
95
+ })
96
+ : connections.begin(owner, {
97
+ requestId,
98
+ name: input.name,
99
+ surface,
100
+ credential: { kind: "static", placement: "bearer" },
101
+ secret: input.bearer,
102
+ }));
81
103
  return {
82
- serverId: connectionId,
83
- name: input.name,
84
- url,
85
- hasBearer: input.bearer !== null,
104
+ connectionId: begun.connectionId,
105
+ authorizeUrl: begun.authorizeUrl,
86
106
  };
87
107
  }
88
108
  catch (cause) {
89
- if (cause instanceof ConnectionsError &&
90
- (cause.code === "invalid_input" || cause.code === "denied"))
109
+ if (cause instanceof ConnectionsError) {
110
+ if (cause.code === "conflict")
111
+ return { error: "duplicate_name" };
112
+ if (cause.code === "invalid_input" || cause.code === "denied")
113
+ return { error: "invalid_endpoint" };
114
+ }
115
+ throw cause;
116
+ }
117
+ }
118
+ /** Give an Agent access, or change how much it has; its next call sees the change. */
119
+ async function grant(connectionId, agentId, access) {
120
+ if (!options.hasAgent(agentId))
121
+ return { error: "not_found" };
122
+ const all = await list();
123
+ const connection = all.find((row) => row.connectionId === connectionId);
124
+ if (connection === undefined)
125
+ return { error: "not_found" };
126
+ const held = connection.grants.some((entry) => entry.agentId === agentId);
127
+ if (!held &&
128
+ all.filter((row) => row.grants.some((entry) => entry.agentId === agentId))
129
+ .length >= maxAgentConnections)
130
+ return { error: "limit" };
131
+ try {
132
+ await run(connections.grant(owner, {
133
+ connectionId,
134
+ agentId,
135
+ tools: toolsFor(access),
136
+ }));
137
+ }
138
+ catch (cause) {
139
+ if (cause instanceof ConnectionsError && cause.code === "invalid_input")
91
140
  return { error: "invalid_endpoint" };
92
141
  throw cause;
93
142
  }
143
+ await options.notify(agentId);
144
+ return { ok: true };
94
145
  }
95
- async function remove(agentId, serverId) {
96
- const current = await servers(agentId);
97
- if (current?.some((server) => server.serverId === serverId) !== true)
146
+ async function ungrant(connectionId, agentId) {
147
+ if (!(await holdersOf(connectionId)).includes(agentId))
98
148
  return false;
99
- const holders = (await run(connections.list(owner))).flatMap((row) => row.connectionId === serverId ? row.grants.map((g) => g.agentId) : []);
100
- await run(connections.revoke(owner, { connectionId: serverId }));
101
- await Promise.all(holders.map((holder) => options.notify(holder)));
149
+ await run(connections.ungrant(owner, { connectionId, agentId }));
150
+ await options.notify(agentId);
102
151
  return true;
103
152
  }
104
- /** Complete one Agent request on the owner side: the only place a credential opens. */
105
- async function fetchFor(agentId, ref, data) {
153
+ /** The tool names an MCP connection offers. */
154
+ async function tools(connectionId) {
106
155
  try {
107
- const init = {
108
- method: data.method,
109
- headers: data.headers.map(([name, value]) => [name, value]),
110
- redirect: "error",
111
- };
112
- if (data.body !== null)
113
- init.body = data.body;
114
- return await connections.egress(agentId, ref)(new Request(data.url, init));
156
+ return await run(connections.tools(owner, connectionId));
157
+ }
158
+ catch (cause) {
159
+ if (cause instanceof ConnectionsError)
160
+ return { error: "not_found" };
161
+ throw cause;
162
+ }
163
+ }
164
+ /** The browser's return from the authorization server; the Agent drops stale tools. */
165
+ async function complete(query) {
166
+ try {
167
+ const { connectionId } = await run(connections.complete(owner, query));
168
+ const holders = (await run(connections.list(owner))).flatMap((row) => row.connectionId === connectionId
169
+ ? row.grants.map((grant) => grant.agentId)
170
+ : []);
171
+ await Promise.all(holders.map((holder) => options.notify(holder)));
172
+ return { ok: true };
115
173
  }
116
174
  catch (cause) {
117
175
  if (cause instanceof ConnectionsError)
@@ -119,52 +177,38 @@ export function createAgentMcpConnections(options) {
119
177
  throw cause;
120
178
  }
121
179
  }
122
- return { servers, add, remove, projection, fetch: fetchFor };
180
+ async function remove(connectionId) {
181
+ const holders = await holdersOf(connectionId);
182
+ const known = (await list()).some((row) => row.connectionId === connectionId);
183
+ if (!known)
184
+ return false;
185
+ await run(connections.revoke(owner, { connectionId }));
186
+ await Promise.all(holders.map((holder) => options.notify(holder)));
187
+ return true;
188
+ }
189
+ /** Complete one Agent request on the owner side: the only place a credential opens. */
190
+ const fetchFor = (agentId, ref, data) => answerMcpRequest(connections.egress, agentId, ref, data);
191
+ return {
192
+ list,
193
+ add,
194
+ grant,
195
+ ungrant,
196
+ remove,
197
+ tools,
198
+ complete,
199
+ projection,
200
+ fetch: fetchFor,
201
+ };
123
202
  }
124
203
  /**
125
204
  * The Agent half: Knapsack connects to each granted server through a fetch that
126
205
  * is completed by the owner. No header, token or locator is ever held here.
127
206
  */
128
207
  export function agentMcpSourceOptions(input) {
129
- const refs = new Map();
130
208
  return {
131
209
  id: "agent-mcp",
132
- read: async () => {
133
- const granted = await input.read();
134
- refs.clear();
135
- const list = granted.connections.flatMap((connection) => {
136
- if (connection.surface.kind !== "mcp")
137
- return [];
138
- refs.set(new URL(connection.surface.url).href, {
139
- connectionId: connection.connectionId,
140
- grantVersion: connection.grantVersion,
141
- });
142
- return [
143
- {
144
- id: `mcp.${connection.connectionId}`,
145
- name: connection.name,
146
- url: new URL(connection.surface.url),
147
- },
148
- ];
149
- });
150
- return {
151
- // Secret-free: ids, versions and endpoints.
152
- version: JSON.stringify(granted.connections.map((c) => [
153
- c.connectionId,
154
- c.grantVersion,
155
- c.authorityVersion,
156
- ])),
157
- servers: list,
158
- };
159
- },
210
+ ...mcpAgentSource({ read: input.read, fetch: input.fetch }),
160
211
  subscribe: input.subscribe,
161
212
  onUnavailable: input.onUnavailable,
162
- fetch: (url, init) => {
163
- const request = new Request(url, init);
164
- const ref = refs.get(request.url);
165
- return ref === undefined
166
- ? Promise.reject(new Error("MCP server is not connected"))
167
- : input.fetch(ref, request);
168
- },
169
213
  };
170
214
  }