@agentage/extension 0.15.2 → 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.
- package/dist/api/files-registry.d.ts +17 -0
- package/dist/api/files-registry.js +10 -0
- package/dist/api/files.d.ts +8 -0
- package/dist/api/files.js +82 -0
- package/dist/api/routes.d.ts +6 -0
- package/dist/api/routes.js +3 -1
- package/dist/auth/token-check.d.ts +1 -1
- package/dist/auth/verify-token.js +9 -9
- package/dist/context/test-context.d.ts +5 -1
- package/dist/context/test-context.js +2 -1
- package/dist/host/daemon/child.js +6 -4
- package/dist/host/daemon/health-routes.js +13 -8
- package/dist/host/daemon/routes.js +3 -1
- package/dist/host/daemon/seal.d.ts +6 -2
- package/dist/host/daemon/seal.js +9 -2
- package/dist/host/host-env.d.ts +1 -0
- package/dist/host/host-env.js +2 -0
- package/dist/host/host-extension.d.ts +1 -0
- package/dist/host/host-extension.js +7 -3
- package/dist/host/host-git-store.d.ts +10 -0
- package/dist/host/host-git-store.js +36 -0
- package/dist/host/host-migrations.d.ts +8 -0
- package/dist/host/host-migrations.js +62 -0
- package/dist/host/host-parts.d.ts +2 -2
- package/dist/host/host-parts.js +1 -1
- package/dist/host/host-url-store.d.ts +22 -0
- package/dist/host/host-url-store.js +62 -0
- package/dist/host/main.js +9 -3
- package/dist/host/serve-host.js +3 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/manifest/primitives.schema.js +1 -1
- package/dist/mcp/connector.d.ts +4 -0
- package/dist/mcp/connector.js +11 -0
- package/dist/mcp/mcp-app.d.ts +3 -1
- package/dist/mcp/mcp-app.js +27 -17
- package/dist/mcp/server.d.ts +6 -3
- package/dist/mcp/server.js +52 -14
- package/dist/mcp/tools.d.ts +22 -4
- package/dist/mcp/tools.js +22 -12
- package/dist/runtime/part-mounts.js +12 -6
- package/dist/server/api-routes.d.ts +5 -2
- package/dist/server/api-routes.js +8 -6
- package/dist/server/app.d.ts +3 -0
- package/dist/server/app.js +11 -1
- package/dist/store/clickhouse-http.d.ts +20 -0
- package/dist/store/clickhouse-http.js +90 -0
- package/dist/store/clickhouse-store.d.ts +22 -0
- package/dist/store/clickhouse-store.js +87 -0
- package/dist/store/git-env.d.ts +11 -0
- package/dist/store/git-env.js +44 -0
- package/dist/store/migrate.js +1 -3
- package/dist/store/store-url.d.ts +4 -0
- package/dist/store/store-url.js +30 -0
- package/dist/store/store.d.ts +1 -0
- package/dist/store/store.js +2 -0
- package/dist/store/store.types.d.ts +3 -0
- package/dist/store/store.types.js +1 -1
- package/dist/testing/test-server.js +11 -12
- package/dist/tool/container-recipe.d.ts +5 -2
- package/dist/tool/container-recipe.js +6 -5
- package/dist/tool/container-stage.js +1 -1
- package/dist/tool/record-extras.js +4 -3
- package/dist/tool/rules/store.js +0 -3
- package/dist/tool/rules/surface.js +4 -1
- package/package.json +1 -1
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type HealthCheck } from '../health/health.js';
|
|
2
|
+
import { type Log } from '../log/log.js';
|
|
3
|
+
import { type ExtensionPackage } from '../manifest/manifest.schema.js';
|
|
4
|
+
import { type PoolStore } from '../store/store.js';
|
|
5
|
+
import { type UrlStoreKind } from '../store/store-url.js';
|
|
6
|
+
import { type Store } from '../store/store.types.js';
|
|
7
|
+
export interface HostStore extends Store {
|
|
8
|
+
close(): Promise<void>;
|
|
9
|
+
readonly kind?: UrlStoreKind | 'git';
|
|
10
|
+
readonly probe?: HealthCheck;
|
|
11
|
+
readonly checks?: Record<string, HealthCheck>;
|
|
12
|
+
}
|
|
13
|
+
export interface UrlStoreAt {
|
|
14
|
+
dir: string;
|
|
15
|
+
file?: string;
|
|
16
|
+
openMs: number;
|
|
17
|
+
}
|
|
18
|
+
type Pool = (url: string, log: Log) => PoolStore;
|
|
19
|
+
export declare const postgresStore: (url: string, dir: string, log: Log, pool?: Pool) => HostStore;
|
|
20
|
+
export declare const openUrlStore: (pkg: ExtensionPackage, at: UrlStoreAt, log: Log) => Promise<HostStore | undefined>;
|
|
21
|
+
export declare const hostStoreChecks: (store: HostStore | undefined) => Record<string, HealthCheck>;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {} from '../health/health.js';
|
|
2
|
+
import { messageOf } from '../log/log.js';
|
|
3
|
+
import {} from '../manifest/manifest.schema.js';
|
|
4
|
+
import { storeOf } from '../manifest/parts.js';
|
|
5
|
+
import { createClickhouseStore } from '../store/clickhouse-store.js';
|
|
6
|
+
import { createStore, storeCheck } from '../store/store.js';
|
|
7
|
+
import { isUrlStoreKind, readStoreUrl, STORE_URL_FILE_ENV, } from '../store/store-url.js';
|
|
8
|
+
import {} from '../store/store.types.js';
|
|
9
|
+
import { migrationsCheck } from './host-migrations.js';
|
|
10
|
+
const poolOf = (url, log) => createStore({ AGENTAGE_STORE_URL: url }, log);
|
|
11
|
+
// The serving host never migrates (the migrate job does): /health is 503 until the ledger is current.
|
|
12
|
+
export const postgresStore = (url, dir, log, pool = poolOf) => {
|
|
13
|
+
const parts = pool(url, log);
|
|
14
|
+
return {
|
|
15
|
+
kind: 'postgres',
|
|
16
|
+
query: parts.query,
|
|
17
|
+
close: () => parts.end(),
|
|
18
|
+
checks: { 'store:migrations': migrationsCheck(parts, dir, log) },
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
const within = (work, ms) => Promise.race([work, new Promise((ok) => setTimeout(() => ok('late'), ms).unref())]);
|
|
22
|
+
// The start waits up to openMs for the store; one that is down still starts, /health says 503.
|
|
23
|
+
const firstUse = async (store, kind, openMs, log) => {
|
|
24
|
+
const opened = store.query('select 1').then(() => 'ok', (err) => err);
|
|
25
|
+
const result = await within(opened, openMs);
|
|
26
|
+
if (result === 'ok')
|
|
27
|
+
return log.info('store opened', { kind, from: STORE_URL_FILE_ENV });
|
|
28
|
+
const reason = result === 'late' ? `not in ${openMs} ms` : messageOf(result);
|
|
29
|
+
log.warn('the store did not open: /health says unavailable until it does', { kind, reason });
|
|
30
|
+
};
|
|
31
|
+
const kindOf = (pkg, log) => {
|
|
32
|
+
const kind = storeOf(pkg);
|
|
33
|
+
if (isUrlStoreKind(kind))
|
|
34
|
+
return kind;
|
|
35
|
+
log.warn(`${STORE_URL_FILE_ENV} is set, the package has no postgres or clickhouse store: unused`);
|
|
36
|
+
return undefined;
|
|
37
|
+
};
|
|
38
|
+
// G1, G2: the estate's store from AGENTAGE_STORE_URL_FILE; unset, the host keeps PGlite (undefined).
|
|
39
|
+
export const openUrlStore = async (pkg, at, log) => {
|
|
40
|
+
if (!at.file)
|
|
41
|
+
return undefined;
|
|
42
|
+
const kind = kindOf(pkg, log);
|
|
43
|
+
if (!kind)
|
|
44
|
+
return undefined;
|
|
45
|
+
const url = await readStoreUrl(at.file, kind);
|
|
46
|
+
const store = kind === 'postgres' ? postgresStore(url, at.dir, log) : createClickhouseStore(url, log);
|
|
47
|
+
await firstUse(store, kind, at.openMs, log);
|
|
48
|
+
return store;
|
|
49
|
+
};
|
|
50
|
+
// Calls that overlap share one run: /health asks checks.store and store:<kind> in one probe.
|
|
51
|
+
const shared = (check) => {
|
|
52
|
+
let running;
|
|
53
|
+
return () => (running ??= check().finally(() => (running = undefined)));
|
|
54
|
+
};
|
|
55
|
+
// checks.store as before; a URL store adds store:<kind> (the same probe) and its own checks.
|
|
56
|
+
export const hostStoreChecks = (store) => {
|
|
57
|
+
if (!store)
|
|
58
|
+
return {};
|
|
59
|
+
const check = shared(store.probe ?? storeCheck(store));
|
|
60
|
+
const named = store.kind ? { [`store:${store.kind}`]: check } : {};
|
|
61
|
+
return { store: check, ...named, ...store.checks };
|
|
62
|
+
};
|
package/dist/host/main.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createLog } from '../log/log.js';
|
|
3
3
|
import { startHostClock } from './clock-rate.js';
|
|
4
|
+
import { migrateHost } from './host-migrations.js';
|
|
4
5
|
import { serveHost } from './serve-host.js';
|
|
5
|
-
// The daemon's child and the one container
|
|
6
|
+
// The daemon's child and the one container, settings from env; `main.js migrate`: the estate's job.
|
|
6
7
|
const crash = (err) => {
|
|
7
8
|
createLog({ extension: 'unknown', part: 'api' }).error(err);
|
|
8
9
|
process.exit(1);
|
|
9
10
|
};
|
|
10
11
|
process.on('uncaughtException', crash);
|
|
11
|
-
|
|
12
|
-
await
|
|
12
|
+
if (process.argv[2] === 'migrate') {
|
|
13
|
+
await migrateHost(process.env).then(() => process.exit(0), crash);
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
startHostClock(process.env);
|
|
17
|
+
await serveHost(process.env).catch(crash);
|
|
18
|
+
}
|
package/dist/host/serve-host.js
CHANGED
|
@@ -52,10 +52,11 @@ export const serveHost = async (env, deps = {}) => {
|
|
|
52
52
|
const at = hostEnvOf(env);
|
|
53
53
|
const guard = guardOf(env, at);
|
|
54
54
|
const hook = exitHook();
|
|
55
|
-
const { dataDir, runDir, settings, origin, secretsDir, storeOpenMs } = at;
|
|
55
|
+
const { dataDir, runDir, settings, origin, secretsDir, storeOpenMs, storeUrlFile } = at;
|
|
56
56
|
// C2: on loopback the child checks Host and Origin itself, for its own port and the daemon's.
|
|
57
57
|
const local = { localOnly: at.bind === '127.0.0.1', localPorts: loopbackPorts(origin) };
|
|
58
|
-
const
|
|
58
|
+
const store = { storeOpenMs, storeUrlFile };
|
|
59
|
+
const opts = { dataDir, runDir, settings, origin, ...store, onExit: hook.onExit, ...local };
|
|
59
60
|
const build = await hostBuildInfo(env, at.dir);
|
|
60
61
|
const host = await hostWith(at.dir, opts, { secretsDir, guard, build });
|
|
61
62
|
const server = await listen(host.app, at.port, at.bind);
|
package/dist/index.d.ts
CHANGED
|
@@ -21,7 +21,9 @@ export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, }
|
|
|
21
21
|
export { versionPage, type PagesContext, type PagesEntry, type PagesSite } from './pages/pages.js';
|
|
22
22
|
export { siteFromDir, type SiteFromDirOptions } from './pages/site-from-dir.js';
|
|
23
23
|
export { type ApiCreate, type ApiHandler, type ApiPart } from './server/part.types.js';
|
|
24
|
+
export { clickhouseOf, createClickhouseStore, isClickhouseOutage, type ClickhouseOptions, type ClickhouseStore, } from './store/clickhouse-store.js';
|
|
24
25
|
export { type QueryResult, type Row, type Store } from './store/store.types.js';
|
|
26
|
+
export { type GitAccess } from './store/git-env.js';
|
|
25
27
|
export { startTestMcp, startTestServer, type TestMcp, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
|
|
26
28
|
export { type JobOptions } from './worker/job-options.js';
|
|
27
29
|
export { type JobRun, type RunStatus } from './worker/runs.js';
|
package/dist/index.js
CHANGED
|
@@ -22,7 +22,9 @@ export {} from './mcp/tools.js';
|
|
|
22
22
|
export { versionPage } from './pages/pages.js';
|
|
23
23
|
export { siteFromDir } from './pages/site-from-dir.js';
|
|
24
24
|
export {} from './server/part.types.js';
|
|
25
|
+
export { clickhouseOf, createClickhouseStore, isClickhouseOutage, } from './store/clickhouse-store.js';
|
|
25
26
|
export {} from './store/store.types.js';
|
|
27
|
+
export {} from './store/git-env.js';
|
|
26
28
|
export { startTestMcp, startTestServer, } from './testing/test-server.js';
|
|
27
29
|
export {} from './worker/job-options.js';
|
|
28
30
|
export {} from './worker/runs.js';
|
|
@@ -51,7 +51,7 @@ export const STORE_KINDS = {
|
|
|
51
51
|
clickhouse: { migrations: false },
|
|
52
52
|
};
|
|
53
53
|
// STORE_KINDS[kind].migrations: the api image carries a migrate job. SERVED_KINDS moves with the estate.
|
|
54
|
-
export const SERVED_KINDS = ['postgres', 'signoz', 'clickhouse'];
|
|
54
|
+
export const SERVED_KINDS = ['postgres', 'signoz', 'git', 'clickhouse'];
|
|
55
55
|
export const StoreKindSchema = z.enum(Object.keys(STORE_KINDS));
|
|
56
56
|
export const FULL_SHA = /^[0-9a-f]{40}$/;
|
|
57
57
|
export const CommitSchema = z.string().regex(FULL_SHA, { message: 'full 40-hex git sha' });
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {} from 'express';
|
|
2
|
+
import { mountMcp } from './mcp-app.js';
|
|
3
|
+
import {} from './tools.js';
|
|
4
|
+
// The connector profile beside the mcp tools: /mcp{rest} becomes /connector{rest}, tools by their own name.
|
|
5
|
+
export const mountWithConnector = (app, options, connectors) => {
|
|
6
|
+
mountMcp(app, options);
|
|
7
|
+
if (connectors.length === 0)
|
|
8
|
+
return;
|
|
9
|
+
const paths = (options.paths ?? ['/mcp']).map((path) => path.replace(/^\/mcp/, '/connector'));
|
|
10
|
+
mountMcp(app, { ...options, tools: connectors, paths, bare: true, instructions: undefined });
|
|
11
|
+
};
|
package/dist/mcp/mcp-app.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { type Express } from 'express';
|
|
2
2
|
import { type PartAppBase } from '../server/app.js';
|
|
3
|
-
import { type ToolEntry } from './tools.js';
|
|
3
|
+
import { type Instructions, type ToolEntry } from './tools.js';
|
|
4
4
|
export interface McpAppOptions extends PartAppBase {
|
|
5
5
|
tools: ToolEntry[];
|
|
6
6
|
listing: 'open' | 'token';
|
|
7
|
+
instructions?: Instructions;
|
|
8
|
+
bare?: boolean;
|
|
7
9
|
paths?: string[];
|
|
8
10
|
}
|
|
9
11
|
export declare const mcpPathOf: (id: string) => string;
|
package/dist/mcp/mcp-app.js
CHANGED
|
@@ -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 {
|
|
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) =>
|
|
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
|
|
51
|
+
return null;
|
|
48
52
|
}
|
|
49
53
|
if (needed.length === 0)
|
|
50
|
-
return
|
|
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
|
|
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) =>
|
|
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
|
|
103
|
+
const caller = await guard(options, req, message, at);
|
|
100
104
|
markRow(options, req, res, message);
|
|
101
|
-
|
|
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
|
|
112
|
-
const
|
|
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) });
|
package/dist/mcp/server.d.ts
CHANGED
|
@@ -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
|
|
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>;
|
package/dist/mcp/server.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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
|
|
42
|
+
const result = resultOf(entry, await entry.handler(argsOf(entry, args), caller));
|
|
32
43
|
log.mcp({ tool, ms: ms() });
|
|
33
|
-
|
|
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
|
|
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
|
|
47
|
-
|
|
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
|
};
|
package/dist/mcp/tools.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
if (
|
|
12
|
-
throw new Error(
|
|
13
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
};
|
package/dist/server/app.d.ts
CHANGED
|
@@ -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;
|