@agentage/extension 0.16.0 → 0.17.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 (52) hide show
  1. package/dist/api/files-registry.d.ts +17 -0
  2. package/dist/api/files-registry.js +10 -0
  3. package/dist/api/files.d.ts +8 -0
  4. package/dist/api/files.js +82 -0
  5. package/dist/api/routes.d.ts +6 -0
  6. package/dist/api/routes.js +3 -1
  7. package/dist/auth/token-check.d.ts +1 -1
  8. package/dist/auth/verify-token.js +9 -9
  9. package/dist/context/test-context.d.ts +5 -1
  10. package/dist/context/test-context.js +2 -1
  11. package/dist/host/daemon/child.js +6 -4
  12. package/dist/host/daemon/health-routes.js +13 -8
  13. package/dist/host/daemon/routes.js +3 -1
  14. package/dist/host/daemon/seal.d.ts +6 -2
  15. package/dist/host/daemon/seal.js +9 -2
  16. package/dist/host/host-extension.js +4 -1
  17. package/dist/host/host-git-store.d.ts +10 -0
  18. package/dist/host/host-git-store.js +36 -0
  19. package/dist/host/host-parts.d.ts +2 -2
  20. package/dist/host/host-parts.js +1 -1
  21. package/dist/host/host-url-store.d.ts +2 -1
  22. package/dist/host/host-url-store.js +1 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/manifest/primitives.schema.js +1 -1
  26. package/dist/mcp/connector.d.ts +4 -0
  27. package/dist/mcp/connector.js +11 -0
  28. package/dist/mcp/mcp-app.d.ts +3 -1
  29. package/dist/mcp/mcp-app.js +27 -17
  30. package/dist/mcp/server.d.ts +6 -3
  31. package/dist/mcp/server.js +52 -14
  32. package/dist/mcp/tools.d.ts +22 -4
  33. package/dist/mcp/tools.js +22 -12
  34. package/dist/runtime/part-mounts.js +12 -6
  35. package/dist/server/api-routes.d.ts +5 -2
  36. package/dist/server/api-routes.js +8 -6
  37. package/dist/server/app.d.ts +3 -0
  38. package/dist/server/app.js +11 -1
  39. package/dist/store/git-env.d.ts +11 -0
  40. package/dist/store/git-env.js +44 -0
  41. package/dist/store/store-url.d.ts +1 -1
  42. package/dist/store/store-url.js +2 -0
  43. package/dist/store/store.types.d.ts +3 -0
  44. package/dist/store/store.types.js +1 -1
  45. package/dist/testing/test-server.js +11 -12
  46. package/dist/tool/container-recipe.d.ts +5 -2
  47. package/dist/tool/container-recipe.js +6 -5
  48. package/dist/tool/container-stage.js +1 -1
  49. package/dist/tool/record-extras.js +4 -3
  50. package/dist/tool/rules/store.js +0 -3
  51. package/dist/tool/rules/surface.js +4 -1
  52. package/package.json +1 -1
@@ -7,9 +7,9 @@ import { requestScope } from '../agcid/current.js';
7
7
  import { setCaller, strongest } from '../auth/token-check.js';
8
8
  import { fail } from '../envelope/envelope.js';
9
9
  import { declaredType, printable } from '../log/who.js';
10
- import { BODY_LIMIT, createPartApp, PUBLIC_CORS } from '../server/app.js';
11
- import { serverFactory } from './server.js';
12
- import { prefixed } from './tools.js';
10
+ import { BODY_LIMIT, createPartApp, PUBLIC_CORS, resourceDocAt, } from '../server/app.js';
11
+ import { authInfoOf, serverFactory } from './server.js';
12
+ import { nameOf } from './tools.js';
13
13
  const MCP_PATH = '/mcp';
14
14
  // The endpoint of an extension on a host that runs many: the daemon routes it to its child.
15
15
  export const mcpPathOf = (id) => `${MCP_PATH}/${id}`;
@@ -34,30 +34,34 @@ const callAccess = (options, body) => messagesOf(body)
34
34
  .filter((message) => message?.method === 'tools/call')
35
35
  .map((message) => {
36
36
  const id = options.pkg.agentage.id;
37
- const entry = options.tools.find((t) => prefixed(id, t.name) === message?.params?.name);
37
+ const entry = options.tools.find((t) => nameOf(id, t.name, options.bare) === message?.params?.name);
38
38
  return entry?.spec.scope ?? 'read';
39
39
  });
40
+ const OPENING = new Set(['initialize', 'server/discover']);
41
+ const isOpening = (body) => messagesOf(body).some((message) => OPENING.has(String(message?.method)));
42
+ // Instructions made per caller: the opening message reads a bearer when one is sent.
43
+ const openingAccess = (options, body) => typeof options.instructions === 'function' && isOpening(body) ? ['optional'] : [];
40
44
  // Tokens off: calls stay anonymous and a closed listing refuses every tools/list (nothing can verify).
41
- const guard = async (options, req, body) => {
45
+ const guard = async (options, req, body, at) => {
42
46
  const listing = options.listing === 'token' && isListing(body) ? ['read'] : [];
43
- const needed = [...listing, ...callAccess(options, body)];
47
+ const needed = [...listing, ...callAccess(options, body), ...openingAccess(options, body)];
44
48
  if (!options.tokenCheck) {
45
49
  if (listing.length > 0)
46
50
  throw fail('UNAUTHORIZED', 'tools/list needs a token');
47
- return false;
51
+ return null;
48
52
  }
49
53
  if (needed.length === 0)
50
- return false;
51
- const caller = await options.tokenCheck(req.get('authorization'), strongest(needed));
54
+ return null;
55
+ const caller = await options.tokenCheck(req.get('authorization'), strongest(needed), at);
52
56
  setCaller(req, caller);
53
- return caller !== null;
57
+ return caller;
54
58
  };
55
59
  // A tools/call leaves its mcp row and no http row (Q1); initialize names the client (Q14).
56
60
  const markRow = (options, req, res, body) => {
57
61
  const messages = messagesOf(body);
58
62
  const scope = requestScope.getStore();
59
63
  const id = options.pkg.agentage.id;
60
- const known = (m) => options.tools.some((t) => prefixed(id, t.name) === m?.params?.name);
64
+ const known = (m) => options.tools.some((t) => nameOf(id, t.name, options.bare) === m?.params?.name);
61
65
  // An unknown tool never reaches a handler, so it keeps its http row.
62
66
  if (messages.some((m) => m?.method === 'tools/call' && known(m))) {
63
67
  res.locals['toolCall'] = true;
@@ -90,15 +94,17 @@ const send = async (response, res, auth) => {
90
94
  return void res.end();
91
95
  await pipeline(Readable.fromWeb(response.body), res);
92
96
  };
93
- const handle = (handler, options) => async (req, res) => {
97
+ const handle = (handler, options, at) => async (req, res) => {
94
98
  const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
95
99
  const message = parsed(body);
96
100
  // The SDK reads a body again when given none (a BOM, say): it must only run what guard read.
97
101
  if (message === undefined)
98
102
  return void res.status(400).json(PARSE_ERROR);
99
- const auth = await guard(options, req, message);
103
+ const caller = await guard(options, req, message, at);
100
104
  markRow(options, req, res, message);
101
- await send(await handler.fetch(webRequest(req, body), { parsedBody: message }), res, auth);
105
+ const authInfo = authInfoOf(caller, isOpening(message));
106
+ const answer = await handler.fetch(webRequest(req, body), { parsedBody: message, authInfo });
107
+ await send(answer, res, caller !== null);
102
108
  };
103
109
  const methodNotAllowed = (_req, res) => {
104
110
  res.setHeader('Allow', 'POST');
@@ -108,16 +114,20 @@ const methodNotAllowed = (_req, res) => {
108
114
  };
109
115
  // Stateless Streamable HTTP on SDK v2: POST only, GET and DELETE (sessions) answer 405.
110
116
  export const mountMcp = (app, options) => {
111
- const identity = { id: options.pkg.agentage.id, version: options.pkg.version };
112
- const handler = createMcpHandler(serverFactory(identity, options.tools, options.log), {
117
+ const { pkg, bare, resource } = options;
118
+ const identity = { id: pkg.agentage.id, version: pkg.version, bare };
119
+ const factory = serverFactory(identity, options.tools, options.log, options.instructions);
120
+ const handler = createMcpHandler(factory, {
113
121
  legacy: 'stateless',
114
122
  onerror: (err) => options.log.warn('mcp request refused', { reason: err.message }),
115
123
  });
116
124
  const raw = express.raw({ type: () => true, limit: BODY_LIMIT });
117
125
  for (const path of options.paths ?? [MCP_PATH]) {
118
126
  app.use(path, cors(MCP_CORS));
119
- app.post(path, raw, handle(handler, options));
127
+ app.post(path, raw, handle(handler, options, path));
120
128
  app.all(path, methodNotAllowed);
129
+ if (resource)
130
+ resourceDocAt(app, path, resource);
121
131
  }
122
132
  };
123
133
  export const createMcpApp = (options) => createPartApp({ ...options, part: 'mcp', mount: (app) => mountMcp(app, options) });
@@ -1,8 +1,11 @@
1
- import { McpServer } from '@modelcontextprotocol/server';
1
+ import { McpServer, type AuthInfo, type McpRequestContext } from '@modelcontextprotocol/server';
2
+ import { type Caller } from '../auth/token-check.js';
2
3
  import { type Log } from '../log/log.js';
3
- import { type ToolEntry } from './tools.js';
4
+ import { type Instructions, type ToolEntry } from './tools.js';
4
5
  export interface ServerIdentity {
5
6
  id: string;
6
7
  version: string;
8
+ bare?: boolean;
7
9
  }
8
- export declare const serverFactory: (identity: ServerIdentity, tools: ToolEntry[], log: Log) => () => McpServer;
10
+ export declare const authInfoOf: (caller: Caller | null, opening: boolean) => AuthInfo;
11
+ export declare const serverFactory: (identity: ServerIdentity, tools: ToolEntry[], log: Log, instructions?: Instructions) => (ctx?: McpRequestContext) => Promise<McpServer>;
@@ -1,9 +1,10 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { agcidOf } from '../agcid/agcid.js';
3
+ import {} from '../auth/token-check.js';
3
4
  import { currentAgcid } from '../agcid/current.js';
4
5
  import { fail, isFailure } from '../envelope/envelope.js';
5
6
  import {} from '../log/log.js';
6
- import { prefixed } from './tools.js';
7
+ import { nameOf } from './tools.js';
7
8
  const text = (value) => [{ type: 'text', text: value }];
8
9
  // A failed tool: isError, the REST error shape, an agcid (minted outside a request); else INTERNAL.
9
10
  const errorResult = (err, log, tool) => {
@@ -24,14 +25,23 @@ const argsOf = (entry, args) => {
24
25
  const fields = new Set(parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'));
25
26
  throw fail('VALIDATION_ERROR', `Invalid arguments: ${[...fields].join(', ')}`);
26
27
  };
27
- const callback = (entry, log, tool) => async (args) => {
28
+ // No output schema: the answer is text only, as a client of a tool with no outputSchema expects.
29
+ const resultOf = (entry, value) => {
30
+ if (!entry.spec.output)
31
+ return { content: text(JSON.stringify(value ?? null)) };
32
+ const output = entry.spec.output.parse(value);
33
+ return {
34
+ content: text(JSON.stringify(output)),
35
+ structuredContent: output,
36
+ };
37
+ };
38
+ const callback = (entry, log, tool, caller) => async (args) => {
28
39
  const start = performance.now();
29
40
  const ms = () => Math.round(performance.now() - start);
30
41
  try {
31
- const output = entry.spec.output.parse(await entry.handler(argsOf(entry, args)));
42
+ const result = resultOf(entry, await entry.handler(argsOf(entry, args), caller));
32
43
  log.mcp({ tool, ms: ms() });
33
- const content = text(JSON.stringify(output));
34
- return { content, structuredContent: output };
44
+ return result;
35
45
  }
36
46
  catch (err) {
37
47
  // A 4xx is a rejection, not a failure: the row stays info.
@@ -39,17 +49,45 @@ const callback = (entry, log, tool) => async (args) => {
39
49
  return errorResult(err, log, tool);
40
50
  }
41
51
  };
52
+ // The caller the guard checked rides in authInfo, the SDK's own path to a per-request server.
53
+ export const authInfoOf = (caller, opening) => ({
54
+ token: '',
55
+ clientId: caller?.sub ?? '',
56
+ scopes: [...(caller?.scopes ?? [])],
57
+ extra: { caller, opening },
58
+ });
59
+ const callerOf = (ctx) => ctx?.authInfo?.extra?.['caller'] ?? null;
60
+ const isOpening = (ctx) => ctx?.authInfo?.extra?.['opening'] === true;
61
+ // Unset fields stay off the listing, so a tool that sets none lists as before.
62
+ const configOf = (spec) => ({
63
+ description: spec.description,
64
+ inputSchema: listedOnly(spec.input),
65
+ ...(spec.output && { outputSchema: spec.output }),
66
+ ...(spec.title !== undefined && { title: spec.title }),
67
+ ...(spec.annotations && { annotations: spec.annotations }),
68
+ });
69
+ // A function runs only for the opening message; its failure is logged and the opening has no text.
70
+ const textOf = async (instructions, ctx, log) => {
71
+ if (typeof instructions !== 'function')
72
+ return instructions;
73
+ if (!isOpening(ctx))
74
+ return undefined;
75
+ try {
76
+ return await instructions(callerOf(ctx));
77
+ }
78
+ catch (err) {
79
+ log.error(err, 'instructions');
80
+ return undefined;
81
+ }
82
+ };
42
83
  // One fresh server per request (stateless); serverInfo agentage-{id} at the package version.
43
- export const serverFactory = (identity, tools, log) => () => {
44
- const server = new McpServer({ name: `agentage-${identity.id}`, version: identity.version });
84
+ export const serverFactory = (identity, tools, log, instructions) => async (ctx) => {
85
+ const caller = callerOf(ctx);
86
+ const info = { name: `agentage-${identity.id}`, version: identity.version };
87
+ const server = new McpServer(info, { instructions: await textOf(instructions, ctx, log) });
45
88
  for (const entry of tools) {
46
- const config = {
47
- description: entry.spec.description,
48
- inputSchema: listedOnly(entry.spec.input),
49
- outputSchema: entry.spec.output,
50
- };
51
- const tool = prefixed(identity.id, entry.name);
52
- server.registerTool(tool, config, callback(entry, log, tool));
89
+ const tool = nameOf(identity.id, entry.name, identity.bare);
90
+ server.registerTool(tool, configOf(entry.spec), callback(entry, log, tool, caller));
53
91
  }
54
92
  return server;
55
93
  };
@@ -1,26 +1,44 @@
1
1
  import { type z } from 'zod';
2
- import { type Access } from '../auth/token-check.js';
2
+ import { type Access, type Caller } from '../auth/token-check.js';
3
3
  import { type PartContext } from '../context/context.js';
4
4
  type ObjectSchema = z.ZodObject;
5
+ export interface ToolAnnotations {
6
+ readOnlyHint?: boolean;
7
+ destructiveHint?: boolean;
8
+ idempotentHint?: boolean;
9
+ openWorldHint?: boolean;
10
+ }
5
11
  export interface ToolSpec<I extends ObjectSchema, O extends ObjectSchema> {
12
+ title?: string;
6
13
  description: string;
7
14
  input: I;
8
- output: O;
15
+ output?: O;
16
+ annotations?: ToolAnnotations;
9
17
  scope?: Exclude<Access, 'optional'>;
10
18
  }
11
- export type ToolHandler<I extends ObjectSchema, O extends ObjectSchema> = (args: z.output<I>) => z.input<O> | Promise<z.input<O>>;
19
+ export type ToolHandler<I extends ObjectSchema, O extends ObjectSchema> = (args: z.output<I>, caller: Caller | null) => z.input<O> | Promise<z.input<O>>;
12
20
  export type ToolRegistrar = <I extends ObjectSchema, O extends ObjectSchema>(name: string, spec: ToolSpec<I, O>, handler: ToolHandler<I, O>) => void;
21
+ export type Instructions = string | ((caller: Caller | null) => string | Promise<string>);
13
22
  export interface McpContext extends PartContext {
14
23
  readonly tool: ToolRegistrar;
24
+ readonly instructions: (instructions: Instructions) => void;
25
+ readonly connector: ToolRegistrar;
15
26
  }
16
27
  export interface ToolEntry {
17
28
  name: string;
18
29
  spec: ToolSpec<ObjectSchema, ObjectSchema>;
19
- handler: (args: Record<string, unknown>) => unknown;
30
+ handler: (args: Record<string, unknown>, caller: Caller | null) => unknown;
20
31
  }
21
32
  export declare const createToolRegistry: () => {
22
33
  tool: ToolRegistrar;
23
34
  tools: ToolEntry[];
35
+ instructions: (value: Instructions) => void;
36
+ served: {
37
+ instructions?: Instructions;
38
+ };
39
+ connector: ToolRegistrar;
40
+ connectors: ToolEntry[];
24
41
  };
25
42
  export declare const prefixed: (id: string, name: string) => string;
43
+ export declare const nameOf: (id: string, name: string, bare?: boolean) => string;
26
44
  export {};
package/dist/mcp/tools.js CHANGED
@@ -3,20 +3,30 @@ import { ACCESS, badScope } from '../auth/token-check.js';
3
3
  import {} from '../context/context.js';
4
4
  const TOOL_NAME = /^[a-z][a-z0-9_-]*$/;
5
5
  const TOOL_ACCESS = ACCESS.filter((access) => access !== 'optional');
6
+ const registrarOn = (tools) => (name, spec, handler) => {
7
+ if (!TOOL_NAME.test(name))
8
+ throw new Error(`tool name ${name}: lowercase, digits, _ and -`);
9
+ if (tools.some((entry) => entry.name === name))
10
+ throw new Error(`tool ${name} is registered twice`);
11
+ if (!spec.description)
12
+ throw new Error(`tool ${name} needs a description: it routes the model`);
13
+ const bad = badScope(spec.scope, TOOL_ACCESS);
14
+ if (bad)
15
+ throw new Error(`tool ${name} ${bad}`);
16
+ tools.push({ name, spec, handler: handler });
17
+ };
6
18
  export const createToolRegistry = () => {
7
19
  const tools = [];
8
- const tool = (name, spec, handler) => {
9
- if (!TOOL_NAME.test(name))
10
- throw new Error(`tool name ${name}: lowercase, digits, _ and -`);
11
- if (tools.some((entry) => entry.name === name))
12
- throw new Error(`tool ${name} is registered twice`);
13
- if (!spec.description)
14
- throw new Error(`tool ${name} needs a description: it routes the model`);
15
- const bad = badScope(spec.scope, TOOL_ACCESS);
16
- if (bad)
17
- throw new Error(`tool ${name} ${bad}`);
18
- tools.push({ name, spec, handler: handler });
20
+ const connectors = [];
21
+ const served = {};
22
+ const instructions = (value) => {
23
+ if (served.instructions !== undefined)
24
+ throw new Error('instructions are set twice');
25
+ served.instructions = value;
19
26
  };
20
- return { tool, tools };
27
+ const [tool, connector] = [registrarOn(tools), registrarOn(connectors)];
28
+ return { tool, tools, instructions, served, connector, connectors };
21
29
  };
22
30
  export const prefixed = (id, name) => `${id}__${name}`;
31
+ // A connector tool keeps its own name (search, fetch); every other is {id}__{name}.
32
+ export const nameOf = (id, name, bare) => bare ? name : prefixed(id, name);
@@ -10,7 +10,8 @@ import {} from '../manifest/manifest.schema.js';
10
10
  import { hasStore } from '../manifest/parts.js';
11
11
  import {} from '../manifest/primitives.schema.js';
12
12
  import { createSpan } from '../log/span.js';
13
- import { mountMcp } from '../mcp/mcp-app.js';
13
+ import { mountWithConnector } from '../mcp/connector.js';
14
+ import {} from '../mcp/mcp-app.js';
14
15
  import { createToolRegistry } from '../mcp/tools.js';
15
16
  import { mountApiRoutes } from '../server/app.js';
16
17
  import { mountApi } from '../server/api-routes.js';
@@ -22,22 +23,27 @@ import {} from './build-info.js';
22
23
  export const callCreate = async (input, part, ctx) => (await loadCreate(input.dir, input.pkg, part, input.importModule))(ctx);
23
24
  const api = async (input) => {
24
25
  const ctx = input.ctx();
25
- const { router, routes, documents } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
26
+ const mounted = await mountApi(ctx, (api) => callCreate(input, 'api', api));
27
+ const { router, routes, documents, files } = mounted;
26
28
  // Declared routes guard at their own scope, whatever the committed file says.
27
29
  const openapi = routes.length > 0 ? generatedOpenapi(input.pkg, routes) : input.openapi;
28
- const options = { ...input.base, router, routes, openapi, wellKnown: documents };
30
+ const options = { ...input.base, router, routes, openapi, wellKnown: documents, files };
29
31
  const record = openapi ? { openapi: openapiPath(input.pkg.agentage.id) } : {};
30
32
  return { mount: (app) => mountApiRoutes(app, { ...options, aliases: input.apiAliases }), record };
31
33
  };
32
34
  const mcp = async (input) => {
33
35
  const registry = createToolRegistry();
34
36
  const ctx = input.ctx();
35
- await callCreate(input, 'mcp', { ...ctx, tool: registry.tool });
37
+ const { tool, instructions, connector, tools: registered, served } = registry;
38
+ await callCreate(input, 'mcp', { ...ctx, tool, instructions, connector });
36
39
  const token = !input.openListing && ctx.settings['mcp.listing'] === 'token';
37
40
  const listing = token ? 'token' : 'open';
38
- const options = { ...input.base, tools: registry.tools, listing, paths: input.mcpPaths };
41
+ const paths = input.mcpPaths;
42
+ const options = { ...input.base, tools: registered, listing, paths, ...served };
43
+ const mount = (app) => mountWithConnector(app, options, registry.connectors);
44
+ // Connector tools stay out of the record: the record lists the {id}__{name} tools only.
39
45
  const tools = toolRecords(input.pkg.agentage.id, registry.tools);
40
- return { mount: (app) => mountMcp(app, options), record: tools.length ? { tools } : {} };
46
+ return { mount, record: tools.length ? { tools } : {} };
41
47
  };
42
48
  const worker = async (input) => {
43
49
  const ctx = input.ctx();
@@ -1,9 +1,12 @@
1
+ import { type FilesEntry } from '../api/files-registry.js';
1
2
  import { type ApiContext, type RouteEntry } from '../api/routes.js';
2
3
  import { type WellKnownEntry } from '../api/well-known.js';
3
4
  import { type PartContext } from '../context/context.js';
4
5
  import { type ApiHandler } from './part.types.js';
5
- export declare const mountApi: (ctx: PartContext, create: (ctx: ApiContext) => unknown) => Promise<{
6
+ export interface MountedApi {
6
7
  router: ApiHandler;
7
8
  routes: RouteEntry[];
8
9
  documents: WellKnownEntry[];
9
- }>;
10
+ files?: FilesEntry;
11
+ }
12
+ export declare const mountApi: (ctx: PartContext, create: (ctx: ApiContext) => unknown) => Promise<MountedApi>;
@@ -1,5 +1,6 @@
1
1
  import { Router } from 'express';
2
2
  import { inQuery } from '../api/openapi-doc.js';
3
+ import {} from '../api/files-registry.js';
3
4
  import { createRouteRegistry } from '../api/routes.js';
4
5
  import {} from '../api/well-known.js';
5
6
  import {} from '../context/context.js';
@@ -47,11 +48,11 @@ const routesRouter = (ctx, routes) => {
47
48
  router[entry.method](expressPath(entry.path), handlerOf(ctx, entry));
48
49
  return router;
49
50
  };
50
- // What create(ctx) gave: its ctx.route routes, or the router it returned; exactly one.
51
- const handlerFor = (ctx, routes, returned) => {
51
+ // What create(ctx) gave: its ctx.route routes, or the router it returned; exactly one (or ctx.files alone).
52
+ const handlerFor = (ctx, routes, returned, files) => {
52
53
  if (routes.length > 0 && returned)
53
54
  throw new Error('the api part registers ctx.route routes and returns a router: pick one');
54
- if (routes.length > 0)
55
+ if (routes.length > 0 || (files && !returned))
55
56
  return routesRouter(ctx, routes);
56
57
  if (!returned)
57
58
  throw new Error('the api part registers nothing and returns no router');
@@ -59,7 +60,8 @@ const handlerFor = (ctx, routes, returned) => {
59
60
  };
60
61
  // Runs the api part's create(ctx) with ctx.route; the runtime and the test server mount alike.
61
62
  export const mountApi = async (ctx, create) => {
62
- const { route, routes, wellKnown, documents } = createRouteRegistry();
63
- const returned = await create({ ...ctx, route, wellKnown });
64
- return { router: handlerFor(ctx, routes, returned), routes, documents };
63
+ const { route, routes, wellKnown, documents, files, filesServed } = createRouteRegistry();
64
+ const returned = await create({ ...ctx, route, wellKnown, files });
65
+ const router = handlerFor(ctx, routes, returned, filesServed.files !== undefined);
66
+ return { router, routes, documents, files: filesServed.files };
65
67
  };
@@ -2,6 +2,7 @@ import { type CorsOptions } from 'cors';
2
2
  import { type Express, type RequestHandler } from 'express';
3
3
  import { type HelmetOptions } from 'helmet';
4
4
  import { type WellKnownEntry } from '../api/well-known.js';
5
+ import { type FilesEntry } from '../api/files-registry.js';
5
6
  import { type TokenCheck } from '../auth/token-check.js';
6
7
  import { type BuildInfo, type ServedRecord } from '../discovery/discovery.js';
7
8
  import { type HealthCheck } from '../health/health.js';
@@ -40,9 +41,11 @@ export interface ApiAppOptions extends PartAppBase {
40
41
  path: string;
41
42
  }[];
42
43
  aliases?: string[];
44
+ files?: FilesEntry;
43
45
  }
44
46
  export declare const PUBLIC_CORS: CorsOptions;
45
47
  export declare const BODY_LIMIT = "1mb";
48
+ export declare const resourceDocAt: (app: Express, path: string, resource: Record<string, unknown>) => void;
46
49
  export declare const createPartApp: (options: PartAppOptions) => Express;
47
50
  export declare const mountApiRoutes: (app: Express, options: ApiAppOptions) => void;
48
51
  export declare const createApiApp: (options: ApiAppOptions) => Express;
@@ -3,6 +3,8 @@ import express, {} from 'express';
3
3
  import helmet, {} from 'helmet';
4
4
  import {} from '../api/well-known.js';
5
5
  import { agcidMiddleware } from '../agcid/scope.js';
6
+ import { mountFiles } from '../api/files.js';
7
+ import {} from '../api/files-registry.js';
6
8
  import { routeAccess, sameShape } from '../auth/route-access.js';
7
9
  import { setCaller } from '../auth/token-check.js';
8
10
  import { discoveryDocument, recordOf, } from '../discovery/discovery.js';
@@ -54,6 +56,11 @@ const healthHandler = (options) => createHealthHandler({
54
56
  parts: options.parts,
55
57
  clockRate: options.clockRate,
56
58
  });
59
+ // RFC 9728 path form: the document of the resource at {path}, the one a 401 there names.
60
+ export const resourceDocAt = (app, path, resource) => {
61
+ const doc = { ...resource, resource: `${String(resource['resource'])}${path}` };
62
+ app.get(`/.well-known/oauth-protected-resource${path}`, (_req, res) => void res.json(doc));
63
+ };
57
64
  // The kit app every part image runs: agcid, headers, /health, discovery, the part, the envelope.
58
65
  export const createPartApp = (options) => {
59
66
  const app = express();
@@ -107,7 +114,10 @@ const routeGuard = (options) => {
107
114
  };
108
115
  // The api routes on an app: the part's own (createApiApp) or the host's one app of all parts.
109
116
  export const mountApiRoutes = (app, options) => {
110
- const prefixes = [apiPrefix(options.pkg.agentage.id), ...(options.aliases ?? [])];
117
+ const { id } = options.pkg.agentage;
118
+ if (options.files)
119
+ mountFiles(app, id, options.files, options.tokenCheck);
120
+ const prefixes = [apiPrefix(id), ...(options.aliases ?? [])];
111
121
  app.use(prefixes, cors(PUBLIC_CORS));
112
122
  for (const { name, render } of options.wellKnown ?? [])
113
123
  app.get(`/.well-known/${name}`, wellKnownHandler(render));
@@ -0,0 +1,11 @@
1
+ export interface GitAccess {
2
+ readonly remote?: string;
3
+ readonly cwd: string;
4
+ readonly env: Readonly<Record<string, string>>;
5
+ }
6
+ export declare const splitCredential: (url: string) => {
7
+ remote: string;
8
+ header?: string;
9
+ };
10
+ export declare const gitEnvOf: (root: string, remote?: string, header?: string) => Record<string, string>;
11
+ export declare const gitAccessOf: (root: string, url?: string) => GitAccess;
@@ -0,0 +1,44 @@
1
+ import { inspect } from 'node:util';
2
+ // The URL of the estate file holds user:password; git gets it as a header, never in a URL or argv.
3
+ export const splitCredential = (url) => {
4
+ const parsed = new URL(url);
5
+ const user = decodeURIComponent(parsed.username);
6
+ const password = decodeURIComponent(parsed.password);
7
+ parsed.username = '';
8
+ parsed.password = '';
9
+ if (!user && !password)
10
+ return { remote: parsed.href };
11
+ const basic = Buffer.from(`${user}:${password}`).toString('base64');
12
+ return { remote: parsed.href, header: `Authorization: Basic ${basic}` };
13
+ };
14
+ // No host or user config, no hooks, no ext:: transport, no prompt; only PATH from the parent.
15
+ const configOf = (remote, header) => [
16
+ ['core.hooksPath', '/dev/null'],
17
+ ...(remote && header ? [[`http.${remote}.extraHeader`, header]] : []),
18
+ ];
19
+ export const gitEnvOf = (root, remote, header) => {
20
+ const config = configOf(remote, header);
21
+ const env = {
22
+ PATH: process.env['PATH'] ?? '/usr/bin:/bin',
23
+ HOME: root,
24
+ GIT_CONFIG_NOSYSTEM: '1',
25
+ GIT_CONFIG_GLOBAL: '/dev/null',
26
+ GIT_TERMINAL_PROMPT: '0',
27
+ GIT_ALLOW_PROTOCOL: 'file:http:https',
28
+ GIT_CONFIG_COUNT: String(config.length),
29
+ };
30
+ config.forEach(([key, value], i) => {
31
+ env[`GIT_CONFIG_KEY_${i}`] = key;
32
+ env[`GIT_CONFIG_VALUE_${i}`] = value;
33
+ });
34
+ return env;
35
+ };
36
+ // A log line or a JSON dump of ctx.store shows no env, so it shows no credential.
37
+ export const gitAccessOf = (root, url) => {
38
+ const { remote, header } = url ? splitCredential(url) : { remote: undefined, header: undefined };
39
+ const shown = { ...(remote && { remote }), cwd: root, env: '[redacted]' };
40
+ return Object.defineProperties({ ...(remote && { remote }), cwd: root, env: gitEnvOf(root, remote, header) }, {
41
+ toJSON: { value: () => shown },
42
+ [inspect.custom]: { value: () => shown },
43
+ });
44
+ };
@@ -1,4 +1,4 @@
1
1
  export declare const STORE_URL_FILE_ENV = "AGENTAGE_STORE_URL_FILE";
2
2
  export type UrlStoreKind = 'postgres' | 'clickhouse';
3
3
  export declare const isUrlStoreKind: (kind: string | undefined) => kind is UrlStoreKind;
4
- export declare const readStoreUrl: (file: string, kind: UrlStoreKind, read?: (at: string) => Promise<string>) => Promise<string>;
4
+ export declare const readStoreUrl: (file: string, kind: UrlStoreKind | "git", read?: (at: string) => Promise<string>) => Promise<string>;
@@ -1,9 +1,11 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { messageOf } from '../log/log.js';
3
3
  export const STORE_URL_FILE_ENV = 'AGENTAGE_STORE_URL_FILE';
4
+ // git reads its URL too, as the remote of its repos (the host opens the repos in dataDir).
4
5
  const SCHEMES = {
5
6
  postgres: { protocol: /^postgres(ql)?:$/, form: 'postgres://' },
6
7
  clickhouse: { protocol: /^https?:$/, form: 'http:// or https://' },
8
+ git: { protocol: /^https?:$/, form: 'http:// or https://' },
7
9
  };
8
10
  export const isUrlStoreKind = (kind) => kind === 'postgres' || kind === 'clickhouse';
9
11
  const refused = (file, why) => new Error(`${STORE_URL_FILE_ENV} ${file}: ${why}`);
@@ -1,7 +1,10 @@
1
+ import { type GitAccess } from './git-env.js';
1
2
  export type Row = Record<string, unknown>;
2
3
  export interface QueryResult<R extends Row = Row> {
3
4
  rows: R[];
4
5
  }
5
6
  export interface Store {
6
7
  query<R extends Row = Row>(text: string, params?: unknown[]): Promise<QueryResult<R>>;
8
+ readonly gitRoot?: string;
9
+ readonly git?: GitAccess;
7
10
  }
@@ -1 +1 @@
1
- export {};
1
+ import {} from './git-env.js';
@@ -6,11 +6,11 @@ import { callerOf } from '../auth/token-check.js';
6
6
  import {} from '../context/context.js';
7
7
  import { createTestContext } from '../context/test-context.js';
8
8
  import {} from '../manifest/manifest.schema.js';
9
- import { createMcpApp } from '../mcp/mcp-app.js';
9
+ import { mountWithConnector } from '../mcp/connector.js';
10
10
  import { callTool } from '../mcp/snapshot.js';
11
11
  import { createToolRegistry, prefixed } from '../mcp/tools.js';
12
12
  import { mountApi } from '../server/api-routes.js';
13
- import { createApiApp } from '../server/app.js';
13
+ import { createApiApp, createPartApp } from '../server/app.js';
14
14
  import {} from '../server/part.types.js';
15
15
  import { listen } from '../server/serve.js';
16
16
  import { KIT_VERSION } from '../tool/kit-version.js';
@@ -42,22 +42,21 @@ export const startTestServer = async (options) => {
42
42
  tokenCheck: callerCheck(ctx.extension.id, options.caller ?? null),
43
43
  openapi: generatedOpenapi(pkg, mounted.routes),
44
44
  };
45
- const base = { pkg, build: TEST_BUILD, log: ctx.log, wellKnown: mounted.documents };
45
+ const { documents: wellKnown, files } = mounted;
46
+ const base = { pkg, build: TEST_BUILD, log: ctx.log, wellKnown, files };
46
47
  return startOn(createApiApp({ ...base, router: mounted.router, routes: mounted.routes, ...guard }));
47
48
  };
48
- // Runs an mcp part's create(ctx) inside the kit's real /mcp app: tools named {id}__{name}.
49
+ // Runs an mcp part's create(ctx) inside the kit's real /mcp app: tools named {id}__{name}; connector tools at /connector.
49
50
  export const startTestMcp = async (options) => {
50
51
  const ctx = options.ctx ?? createTestContext();
51
52
  const registry = createToolRegistry();
52
- await options.create({ ...ctx, tool: registry.tool });
53
+ const { tool, instructions, connector } = registry;
54
+ await options.create({ ...ctx, tool, instructions, connector });
53
55
  const pkg = testPackage(ctx, { mcp: true });
54
- const app = createMcpApp({
55
- pkg,
56
- build: TEST_BUILD,
57
- log: ctx.log,
58
- tools: registry.tools,
59
- listing: 'open',
60
- });
56
+ const base = { pkg, build: TEST_BUILD, log: ctx.log, tools: registry.tools };
57
+ const mcp = { ...base, listing: 'open', ...registry.served };
58
+ const mount = (app) => mountWithConnector(app, mcp, registry.connectors);
59
+ const app = createPartApp({ ...mcp, part: 'mcp', mount });
61
60
  const server = await startOn(app);
62
61
  const call = (name, args = {}) => callTool(`${server.url}/mcp`, prefixed(ctx.extension.id, name), args);
63
62
  return { ...server, call };
@@ -1,4 +1,7 @@
1
1
  export declare const CONTAINER_PORT = 8080;
2
- export declare const containerRecipe: ({ pglite }: {
2
+ interface Stores {
3
3
  pglite?: string;
4
- }) => string;
4
+ git?: boolean;
5
+ }
6
+ export declare const containerRecipe: (stores: Stores) => string;
7
+ export {};
@@ -32,17 +32,18 @@ const runnerEnv = (store) => [
32
32
  ' COMMIT_SHA=$COMMIT_SHA \\',
33
33
  ' BUILD_TIME=$BUILD_TIME',
34
34
  ];
35
- const runner = (store) => [
36
- ...runnerEnv(store),
35
+ const runner = ({ pglite, git }) => [
36
+ ...runnerEnv(pglite !== undefined || Boolean(git)),
37
+ ...(git ? ['RUN apk add --no-cache git'] : []),
37
38
  'WORKDIR /app',
38
39
  'COPY --from=deps /app/node_modules ./node_modules',
39
- ...(store
40
+ ...(pglite !== undefined
40
41
  ? [
41
42
  'COPY --from=pglite /pglite/node_modules/@electric-sql/pglite ./node_modules/@electric-sql/pglite',
42
43
  ]
43
44
  : []),
44
45
  'COPY app/ ./',
45
- ...(store
46
+ ...(pglite !== undefined || git
46
47
  ? [`RUN mkdir -p ${DATA_VOLUME} && chown node:node ${DATA_VOLUME}`, `VOLUME ${DATA_VOLUME}`]
47
48
  : []),
48
49
  'USER node',
@@ -52,4 +53,4 @@ const runner = (store) => [
52
53
  '',
53
54
  ];
54
55
  // The one image of an extension: the kit host in one process; pglite is set for a postgres store.
55
- export const containerRecipe = ({ pglite }) => [...DEPS, ...(pglite ? pgliteStage(pglite) : []), ...runner(pglite !== undefined)].join('\n');
56
+ export const containerRecipe = (stores) => [...DEPS, ...(stores.pglite ? pgliteStage(stores.pglite) : []), ...runner(stores)].join('\n');