@agentropy/runtime 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +39 -2
- package/dist/a2a-client.d.ts +111 -0
- package/dist/a2a-client.js +386 -0
- package/dist/a2a-history.d.ts +27 -0
- package/dist/a2a-history.js +67 -0
- package/dist/a2a-http.d.ts +46 -0
- package/dist/a2a-http.js +183 -0
- package/dist/a2a-protocol.d.ts +77 -0
- package/dist/a2a-protocol.js +148 -0
- package/dist/a2a-push-receiver.d.ts +24 -0
- package/dist/a2a-push-receiver.js +161 -0
- package/dist/a2a-push.d.ts +85 -0
- package/dist/a2a-push.js +385 -0
- package/dist/a2a-server.d.ts +82 -0
- package/dist/a2a-server.js +523 -0
- package/dist/a2a-sse.d.ts +5 -0
- package/dist/a2a-sse.js +36 -0
- package/dist/a2a.d.ts +41 -0
- package/dist/a2a.js +40 -0
- package/dist/app.d.ts +256 -0
- package/dist/app.js +541 -0
- package/dist/audit.d.ts +229 -0
- package/dist/audit.js +718 -0
- package/dist/bounded-body.d.ts +32 -0
- package/dist/bounded-body.js +124 -0
- package/dist/communication.d.ts +62 -0
- package/dist/communication.js +142 -0
- package/dist/compaction.d.ts +24 -0
- package/dist/compaction.js +202 -0
- package/dist/federation.d.ts +108 -0
- package/dist/federation.js +241 -0
- package/dist/http-path.d.ts +7 -0
- package/dist/http-path.js +14 -0
- package/dist/human-actions.d.ts +62 -0
- package/dist/human-actions.js +359 -0
- package/dist/implementation.d.ts +47 -0
- package/dist/implementation.js +138 -0
- package/dist/inbox.d.ts +101 -0
- package/dist/inbox.js +389 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +32 -0
- package/dist/ingress.d.ts +35 -0
- package/dist/ingress.js +86 -0
- package/dist/lifecycle.d.ts +45 -0
- package/dist/lifecycle.js +57 -0
- package/dist/limits.d.ts +43 -0
- package/dist/limits.js +71 -0
- package/dist/mcp.d.ts +111 -0
- package/dist/mcp.js +308 -0
- package/dist/memory.d.ts +25 -0
- package/dist/memory.js +134 -0
- package/dist/model-routing.d.ts +66 -0
- package/dist/model-routing.js +80 -0
- package/dist/otel.d.ts +60 -0
- package/dist/otel.js +72 -0
- package/dist/outbox.d.ts +116 -0
- package/dist/outbox.js +327 -0
- package/dist/policy-cache.d.ts +69 -0
- package/dist/policy-cache.js +178 -0
- package/dist/priority.d.ts +27 -0
- package/dist/priority.js +28 -0
- package/dist/quotas.d.ts +19 -0
- package/dist/quotas.js +47 -0
- package/dist/reasoning.d.ts +54 -0
- package/dist/reasoning.js +307 -0
- package/dist/registry.d.ts +101 -0
- package/dist/registry.js +369 -0
- package/dist/remote.d.ts +130 -0
- package/dist/remote.js +473 -0
- package/dist/runtime.d.ts +167 -0
- package/dist/runtime.js +1035 -0
- package/dist/skills.d.ts +86 -0
- package/dist/skills.js +376 -0
- package/dist/task-service.d.ts +239 -0
- package/dist/task-service.js +790 -0
- package/dist/tools.d.ts +140 -0
- package/dist/tools.js +476 -0
- package/dist/wake-index.d.ts +9 -0
- package/dist/wake-index.js +11 -0
- package/dist/wakeups.d.ts +142 -0
- package/dist/wakeups.js +501 -0
- package/dist/workflow.d.ts +36 -0
- package/dist/workflow.js +101 -0
- package/package.json +48 -3
package/dist/limits.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface RuntimeLimits {
|
|
2
|
+
/** Concurrent executions per process. */
|
|
3
|
+
poolSize: number;
|
|
4
|
+
/** Execution lease; renewed by the heartbeat: on every tick and, in a started app, on a timer of its own (FIX-051). */
|
|
5
|
+
leaseMs: number;
|
|
6
|
+
/** Time a cancelled handler gets to stop before its lease is fenced. */
|
|
7
|
+
cancelGraceMs: number;
|
|
8
|
+
/**
|
|
9
|
+
* Longest one activation may run (FEAT-037.2). Past it the handler's signal aborts with `Timeout`; a handler that
|
|
10
|
+
* does not stop within `cancelGraceMs` is fenced like a lost lease (retry or fail by the task's retry policy).
|
|
11
|
+
* Long work waits (`waiting`) instead of running long.
|
|
12
|
+
*/
|
|
13
|
+
maxActivationMs: number;
|
|
14
|
+
/** Finished execution records kept per task. */
|
|
15
|
+
keepExecutions: number;
|
|
16
|
+
/** Largest serialized checkpoint. */
|
|
17
|
+
maxCheckpointBytes: number;
|
|
18
|
+
/** Policy decision timeout. */
|
|
19
|
+
pdpTimeoutMs: number;
|
|
20
|
+
/** Delegation depth and children per parent. */
|
|
21
|
+
maxDepth: number;
|
|
22
|
+
maxFanOut: number;
|
|
23
|
+
/** Unconsumed events per subscription. */
|
|
24
|
+
mailboxLimit: number;
|
|
25
|
+
/** Largest serialized task input, task output, inbound event payload and human-action prompt (FEAT-040.2). */
|
|
26
|
+
maxInputBytes: number;
|
|
27
|
+
maxOutputBytes: number;
|
|
28
|
+
maxEventBytes: number;
|
|
29
|
+
maxPromptBytes: number;
|
|
30
|
+
/** ADR-0024 gate retry schedule. */
|
|
31
|
+
gateRetry: {
|
|
32
|
+
initialMs: number;
|
|
33
|
+
maxMs: number;
|
|
34
|
+
maxAttempts: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export declare const DEFAULT_LIMITS: RuntimeLimits;
|
|
38
|
+
/**
|
|
39
|
+
* Refuses a value whose JSON serialization exceeds `max` bytes (`SchemaViolation`, reason `<what>TooLarge`), so a
|
|
40
|
+
* payload cannot grow task rows, mailboxes and inbox entries without bound (FEAT-040.2).
|
|
41
|
+
*/
|
|
42
|
+
export declare function assertMaxBytes(value: unknown, max: number, what: 'input' | 'output' | 'event' | 'prompt'): void;
|
|
43
|
+
export declare function resolveLimits(overrides?: Partial<RuntimeLimits>): RuntimeLimits;
|
package/dist/limits.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Operational limits (D-05, TASK-026.5): one validated view of every bound the runtime enforces, so operators can
|
|
3
|
+
* see and set them in one place. Invalid values fail fast at startup with InvalidConfiguration.
|
|
4
|
+
*/
|
|
5
|
+
import { AgentropyError } from '@agentropy/core';
|
|
6
|
+
export const DEFAULT_LIMITS = {
|
|
7
|
+
poolSize: 4,
|
|
8
|
+
leaseMs: 60_000,
|
|
9
|
+
cancelGraceMs: 30_000,
|
|
10
|
+
maxActivationMs: 600_000,
|
|
11
|
+
keepExecutions: 20,
|
|
12
|
+
maxCheckpointBytes: 64 * 1024,
|
|
13
|
+
pdpTimeoutMs: 5_000,
|
|
14
|
+
maxDepth: 5,
|
|
15
|
+
maxFanOut: 20,
|
|
16
|
+
mailboxLimit: 1_000,
|
|
17
|
+
maxInputBytes: 1024 * 1024,
|
|
18
|
+
maxOutputBytes: 1024 * 1024,
|
|
19
|
+
maxEventBytes: 256 * 1024,
|
|
20
|
+
maxPromptBytes: 16 * 1024,
|
|
21
|
+
gateRetry: { initialMs: 1_000, maxMs: 300_000, maxAttempts: 8 },
|
|
22
|
+
};
|
|
23
|
+
/** Upper bounds that keep a misconfiguration from becoming a resource problem. */
|
|
24
|
+
const BOUNDS = {
|
|
25
|
+
poolSize: [1, 1_024],
|
|
26
|
+
leaseMs: [100, 3_600_000],
|
|
27
|
+
cancelGraceMs: [0, 3_600_000],
|
|
28
|
+
maxActivationMs: [100, 86_400_000],
|
|
29
|
+
keepExecutions: [1, 10_000],
|
|
30
|
+
maxCheckpointBytes: [256, 16 * 1024 * 1024],
|
|
31
|
+
pdpTimeoutMs: [1, 300_000],
|
|
32
|
+
maxDepth: [1, 64],
|
|
33
|
+
maxFanOut: [1, 10_000],
|
|
34
|
+
mailboxLimit: [1, 1_000_000],
|
|
35
|
+
maxInputBytes: [1024, 64 * 1024 * 1024],
|
|
36
|
+
maxOutputBytes: [1024, 64 * 1024 * 1024],
|
|
37
|
+
maxEventBytes: [256, 16 * 1024 * 1024],
|
|
38
|
+
maxPromptBytes: [64, 1024 * 1024],
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Refuses a value whose JSON serialization exceeds `max` bytes (`SchemaViolation`, reason `<what>TooLarge`), so a
|
|
42
|
+
* payload cannot grow task rows, mailboxes and inbox entries without bound (FEAT-040.2).
|
|
43
|
+
*/
|
|
44
|
+
export function assertMaxBytes(value, max, what) {
|
|
45
|
+
const size = Buffer.byteLength(JSON.stringify(value ?? null));
|
|
46
|
+
if (size > max)
|
|
47
|
+
throw new AgentropyError('SchemaViolation', `The ${what} of ${size} bytes exceeds the ${max}-byte limit`, { details: { reason: `${what}TooLarge`, size, limit: max } });
|
|
48
|
+
}
|
|
49
|
+
export function resolveLimits(overrides = {}) {
|
|
50
|
+
const limits = {
|
|
51
|
+
...DEFAULT_LIMITS,
|
|
52
|
+
...overrides,
|
|
53
|
+
gateRetry: { ...DEFAULT_LIMITS.gateRetry, ...overrides.gateRetry },
|
|
54
|
+
};
|
|
55
|
+
const bad = (field, value, range) => new AgentropyError('InvalidConfiguration', `Limit ${field} must be an integer in ${range}`, { details: { field, value: String(value), range } });
|
|
56
|
+
for (const [field, [min, max]] of Object.entries(BOUNDS)) {
|
|
57
|
+
const v = limits[field];
|
|
58
|
+
if (!Number.isInteger(v) || v < min || v > max)
|
|
59
|
+
throw bad(field, v, `[${min}, ${max}]`);
|
|
60
|
+
}
|
|
61
|
+
const g = limits.gateRetry;
|
|
62
|
+
for (const k of ['initialMs', 'maxMs', 'maxAttempts'])
|
|
63
|
+
if (!Number.isInteger(g[k]) || g[k] < 1)
|
|
64
|
+
throw bad(`gateRetry.${k}`, g[k], '[1, ∞)');
|
|
65
|
+
if (g.maxMs < g.initialMs)
|
|
66
|
+
throw bad('gateRetry.maxMs', g.maxMs, `[${g.initialMs}, ∞)`);
|
|
67
|
+
// A lease shorter than the cancel grace would fence a stopping handler early.
|
|
68
|
+
if (limits.cancelGraceMs > limits.leaseMs)
|
|
69
|
+
throw bad('cancelGraceMs', limits.cancelGraceMs, `[0, leaseMs=${limits.leaseMs}]`);
|
|
70
|
+
return Object.freeze({ ...limits, gateRetry: Object.freeze({ ...g }) });
|
|
71
|
+
}
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { type ToolBinding, type ToolDescriptor, type ToolInvocationContext, type ToolProvider } from '@agentropy/core';
|
|
2
|
+
/** The MCP protocol revision this client asks for. */
|
|
3
|
+
export declare const MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
4
|
+
export interface McpCallOptions {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
/** Resolved per invocation by the executor; the transport decides how to present it (e.g. a Bearer token). */
|
|
7
|
+
credential?: unknown;
|
|
8
|
+
}
|
|
9
|
+
/** A JSON-RPC transport to one MCP server. */
|
|
10
|
+
export interface McpTransport {
|
|
11
|
+
request(method: string, params: unknown, options: McpCallOptions): Promise<unknown>;
|
|
12
|
+
notify?(method: string, params: unknown, options: McpCallOptions): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface McpTool {
|
|
15
|
+
name: string;
|
|
16
|
+
description?: string;
|
|
17
|
+
inputSchema: Record<string, unknown>;
|
|
18
|
+
outputSchema?: Record<string, unknown>;
|
|
19
|
+
annotations?: {
|
|
20
|
+
readOnlyHint?: boolean;
|
|
21
|
+
idempotentHint?: boolean;
|
|
22
|
+
destructiveHint?: boolean;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export interface McpCallResult {
|
|
26
|
+
content?: {
|
|
27
|
+
type: string;
|
|
28
|
+
text?: string;
|
|
29
|
+
}[];
|
|
30
|
+
structuredContent?: unknown;
|
|
31
|
+
isError?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export declare class McpClient {
|
|
34
|
+
private readonly transport;
|
|
35
|
+
private ready?;
|
|
36
|
+
constructor(transport: McpTransport);
|
|
37
|
+
/**
|
|
38
|
+
* Runs `fn` on an initialized session. A server that forgot the session (a restart, a session timeout) answers
|
|
39
|
+
* 404; the client then initializes a new session and repeats the request once, as the MCP specification says. A
|
|
40
|
+
* 404 means the request was not processed, so repeating it cannot run a tool twice. A second loss is an error.
|
|
41
|
+
*/
|
|
42
|
+
private inSession;
|
|
43
|
+
private init;
|
|
44
|
+
listTools(o?: McpCallOptions): Promise<McpTool[]>;
|
|
45
|
+
private listAll;
|
|
46
|
+
callTool(name: string, args: unknown, o?: McpCallOptions): Promise<McpCallResult>;
|
|
47
|
+
}
|
|
48
|
+
/** Digest of the parts of a tool the caller's validation depends on. */
|
|
49
|
+
export declare const mcpSchemaDigest: (t: Pick<McpTool, "inputSchema" | "outputSchema">) => string;
|
|
50
|
+
/**
|
|
51
|
+
* A discovered MCP tool as a Tool v1 descriptor and its binding. `idPrefix` namespaces the server's tool names
|
|
52
|
+
* (e.g. `files` → `files.read-file`); `version` is the registered tool version (the MCP server has none per tool).
|
|
53
|
+
*/
|
|
54
|
+
export declare function mcpToolRegistration(tool: McpTool, o: {
|
|
55
|
+
idPrefix: string;
|
|
56
|
+
version: string;
|
|
57
|
+
providerVersion?: string;
|
|
58
|
+
}): {
|
|
59
|
+
descriptor: ToolDescriptor;
|
|
60
|
+
binding: ToolBinding;
|
|
61
|
+
};
|
|
62
|
+
export declare class McpToolProvider implements ToolProvider {
|
|
63
|
+
private readonly client;
|
|
64
|
+
private readonly o;
|
|
65
|
+
readonly id = "mcp";
|
|
66
|
+
readonly version = "1.0.0";
|
|
67
|
+
readonly features: {
|
|
68
|
+
protocol: string;
|
|
69
|
+
protocolVersion: string;
|
|
70
|
+
cancellation: boolean;
|
|
71
|
+
idempotencyKeys: boolean;
|
|
72
|
+
streaming: boolean;
|
|
73
|
+
};
|
|
74
|
+
private listed?;
|
|
75
|
+
constructor(client: McpClient, o?: {
|
|
76
|
+
/** How long a `tools/list` answer is trusted for the schema check (default 5 min). */
|
|
77
|
+
schemaTtlMs?: number;
|
|
78
|
+
now?: () => number;
|
|
79
|
+
});
|
|
80
|
+
private current;
|
|
81
|
+
invoke(binding: ToolBinding, d: ToolDescriptor, input: unknown, ctx: ToolInvocationContext): Promise<unknown>;
|
|
82
|
+
}
|
|
83
|
+
/** The part of a fetch `Response` the HTTP transport reads. */
|
|
84
|
+
export interface McpHttpResponse {
|
|
85
|
+
status: number;
|
|
86
|
+
headers: {
|
|
87
|
+
get(name: string): string | null;
|
|
88
|
+
};
|
|
89
|
+
text(): Promise<string>;
|
|
90
|
+
/** The body stream, when the fetch has one: cancelled when the reply is not read (FIX-085). */
|
|
91
|
+
body?: unknown;
|
|
92
|
+
}
|
|
93
|
+
export type McpFetch = (url: string, init: {
|
|
94
|
+
method: 'POST';
|
|
95
|
+
headers: Record<string, string>;
|
|
96
|
+
body: string;
|
|
97
|
+
signal?: AbortSignal;
|
|
98
|
+
redirect: 'manual';
|
|
99
|
+
}) => Promise<McpHttpResponse>;
|
|
100
|
+
/**
|
|
101
|
+
* Streamable HTTP transport (MCP 2025-06-18): every message is a POST to one endpoint; a reply is JSON or an SSE
|
|
102
|
+
* stream that carries the response; the session ID the server issues at `initialize` is sent on later requests.
|
|
103
|
+
* A credential `{ token }` becomes a Bearer header. Redirects are never followed and replies are size-bounded.
|
|
104
|
+
*/
|
|
105
|
+
export declare function mcpHttpTransport(o: {
|
|
106
|
+
url: string;
|
|
107
|
+
fetch: McpFetch;
|
|
108
|
+
/** Extra static headers (not credentials). */
|
|
109
|
+
headers?: Record<string, string>;
|
|
110
|
+
maxResponseBytes?: number;
|
|
111
|
+
}): McpTransport;
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP client tool provider (FEAT-035.1, R-11): tools of a Model Context Protocol server as Tool v1 tools.
|
|
3
|
+
*
|
|
4
|
+
* - `McpClient` speaks the three methods a tool consumer needs (`initialize`, `tools/list`, `tools/call`) over an
|
|
5
|
+
* `McpTransport`; `mcpHttpTransport` is the Streamable HTTP transport (JSON or SSE replies, session header).
|
|
6
|
+
* - `mcpToolRegistration` turns a discovered MCP tool into a Tool v1 descriptor and binding. MCP has no idempotency
|
|
7
|
+
* key, so a tool with effects is `at-least-once` unless the server marks it `idempotentHint`; a read-only tool is
|
|
8
|
+
* `read`. Discovered tools are candidates: they enter the registry through the normal registration, verification
|
|
9
|
+
* and activation, never automatically.
|
|
10
|
+
* - `McpToolProvider` is the `ToolProvider`: the executor's PEP, policy, audit, timeout and schema checks all apply
|
|
11
|
+
* before and after it. The binding pins a digest of the tool's schemas; if the server's current schemas differ the
|
|
12
|
+
* call fails `IncompatibleVersion` instead of running a changed tool (checked against a cached `tools/list`).
|
|
13
|
+
*
|
|
14
|
+
* Results are data: error text from the server is never copied into errors, only its numeric code.
|
|
15
|
+
*/
|
|
16
|
+
import { createRequire } from 'node:module';
|
|
17
|
+
import { AgentropyError, digestOf, } from '@agentropy/core';
|
|
18
|
+
import { sseData } from './a2a-sse.js';
|
|
19
|
+
import { ReplyTooLarge, readBoundedText, release } from './bounded-body.js';
|
|
20
|
+
/** The MCP protocol revision this client asks for. */
|
|
21
|
+
export const MCP_PROTOCOL_VERSION = '2025-06-18';
|
|
22
|
+
const unavailable = (what, details = {}) => new AgentropyError('ProviderUnavailable', what, {
|
|
23
|
+
details: { kind: 'tool', protocol: 'mcp', ...details },
|
|
24
|
+
});
|
|
25
|
+
/** Version sent as `clientInfo.version`: the runtime package's, read once (`0.0.0` where package.json is not shipped). */
|
|
26
|
+
const CLIENT_VERSION = (() => {
|
|
27
|
+
try {
|
|
28
|
+
const pkg = createRequire(import.meta.url)('../package.json');
|
|
29
|
+
return typeof pkg.version === 'string' ? pkg.version : '0.0.0';
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return '0.0.0';
|
|
33
|
+
}
|
|
34
|
+
})();
|
|
35
|
+
/** The server no longer knows our session (HTTP 404 for a request that carried its ID): start a new one. */
|
|
36
|
+
const sessionLost = (err) => err instanceof AgentropyError &&
|
|
37
|
+
err.details?.sessionLost === true;
|
|
38
|
+
export class McpClient {
|
|
39
|
+
transport;
|
|
40
|
+
ready;
|
|
41
|
+
constructor(transport) {
|
|
42
|
+
this.transport = transport;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Runs `fn` on an initialized session. A server that forgot the session (a restart, a session timeout) answers
|
|
46
|
+
* 404; the client then initializes a new session and repeats the request once, as the MCP specification says. A
|
|
47
|
+
* 404 means the request was not processed, so repeating it cannot run a tool twice. A second loss is an error.
|
|
48
|
+
*/
|
|
49
|
+
async inSession(o, fn) {
|
|
50
|
+
for (let attempt = 0;; attempt++) {
|
|
51
|
+
try {
|
|
52
|
+
await this.init(o);
|
|
53
|
+
return await fn();
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
if (attempt > 0 || !sessionLost(err))
|
|
57
|
+
throw err;
|
|
58
|
+
this.ready = undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
init(o) {
|
|
63
|
+
this.ready ??= (async () => {
|
|
64
|
+
await this.transport.request('initialize', {
|
|
65
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
66
|
+
capabilities: {},
|
|
67
|
+
clientInfo: { name: 'agentropy', version: CLIENT_VERSION },
|
|
68
|
+
}, o);
|
|
69
|
+
await this.transport.notify?.('notifications/initialized', undefined, o);
|
|
70
|
+
})().catch((err) => {
|
|
71
|
+
this.ready = undefined; // a failed handshake is retried by the next call
|
|
72
|
+
throw err;
|
|
73
|
+
});
|
|
74
|
+
return this.ready;
|
|
75
|
+
}
|
|
76
|
+
listTools(o = {}) {
|
|
77
|
+
return this.inSession(o, () => this.listAll(o));
|
|
78
|
+
}
|
|
79
|
+
async listAll(o) {
|
|
80
|
+
const tools = [];
|
|
81
|
+
let cursor;
|
|
82
|
+
for (let page = 0; page < 20; page++) {
|
|
83
|
+
const r = (await this.transport.request('tools/list', cursor ? { cursor } : {}, o));
|
|
84
|
+
for (const t of r?.tools ?? [])
|
|
85
|
+
if (typeof t?.name === 'string' && t.inputSchema)
|
|
86
|
+
tools.push(t);
|
|
87
|
+
cursor = r?.nextCursor;
|
|
88
|
+
if (!cursor)
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
return tools;
|
|
92
|
+
}
|
|
93
|
+
callTool(name, args, o = {}) {
|
|
94
|
+
return this.inSession(o, async () => {
|
|
95
|
+
const r = (await this.transport.request('tools/call', { name, arguments: args }, o));
|
|
96
|
+
if (!r || typeof r !== 'object')
|
|
97
|
+
throw unavailable('Malformed MCP reply');
|
|
98
|
+
return r;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const slug = (s) => s
|
|
103
|
+
.toLowerCase()
|
|
104
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
105
|
+
.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '');
|
|
106
|
+
/** Digest of the parts of a tool the caller's validation depends on. */
|
|
107
|
+
export const mcpSchemaDigest = (t) => digestOf({ input: t.inputSchema, output: t.outputSchema ?? null });
|
|
108
|
+
/**
|
|
109
|
+
* A discovered MCP tool as a Tool v1 descriptor and its binding. `idPrefix` namespaces the server's tool names
|
|
110
|
+
* (e.g. `files` → `files.read-file`); `version` is the registered tool version (the MCP server has none per tool).
|
|
111
|
+
*/
|
|
112
|
+
export function mcpToolRegistration(tool, o) {
|
|
113
|
+
const id = `${slug(o.idPrefix)}.${slug(tool.name)}`;
|
|
114
|
+
const read = tool.annotations?.readOnlyHint === true;
|
|
115
|
+
const descriptor = {
|
|
116
|
+
id,
|
|
117
|
+
version: o.version,
|
|
118
|
+
description: (tool.description ?? tool.name).slice(0, 2000) || tool.name,
|
|
119
|
+
inputSchema: tool.inputSchema,
|
|
120
|
+
...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
|
|
121
|
+
effect: read ? 'read' : 'external',
|
|
122
|
+
// MCP carries no idempotency key: only a server's own idempotent hint lifts the at-least-once default.
|
|
123
|
+
idempotency: read
|
|
124
|
+
? 'idempotent'
|
|
125
|
+
: tool.annotations?.idempotentHint === true
|
|
126
|
+
? 'idempotent'
|
|
127
|
+
: 'at-least-once',
|
|
128
|
+
permission: `tool:${id}:call`,
|
|
129
|
+
};
|
|
130
|
+
const binding = {
|
|
131
|
+
bindingId: 'mcp',
|
|
132
|
+
toolId: id,
|
|
133
|
+
toolVersion: o.version,
|
|
134
|
+
providerId: 'mcp',
|
|
135
|
+
providerVersion: o.providerVersion ?? '1.0.0',
|
|
136
|
+
config: { tool: tool.name, schemaDigest: mcpSchemaDigest(tool) },
|
|
137
|
+
default: true,
|
|
138
|
+
};
|
|
139
|
+
return { descriptor, binding };
|
|
140
|
+
}
|
|
141
|
+
export class McpToolProvider {
|
|
142
|
+
client;
|
|
143
|
+
o;
|
|
144
|
+
id = 'mcp';
|
|
145
|
+
version = '1.0.0';
|
|
146
|
+
features = {
|
|
147
|
+
protocol: 'mcp',
|
|
148
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
149
|
+
cancellation: true,
|
|
150
|
+
idempotencyKeys: false,
|
|
151
|
+
streaming: false,
|
|
152
|
+
};
|
|
153
|
+
listed;
|
|
154
|
+
constructor(client, o = {}) {
|
|
155
|
+
this.client = client;
|
|
156
|
+
this.o = o;
|
|
157
|
+
}
|
|
158
|
+
async current(name, opts) {
|
|
159
|
+
const now = (this.o.now ?? Date.now)();
|
|
160
|
+
if (!this.listed ||
|
|
161
|
+
now - this.listed.at > (this.o.schemaTtlMs ?? 300_000)) {
|
|
162
|
+
const tools = await this.client.listTools(opts);
|
|
163
|
+
this.listed = {
|
|
164
|
+
at: now,
|
|
165
|
+
digests: new Map(tools.map((t) => [t.name, mcpSchemaDigest(t)])),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return this.listed.digests.get(name);
|
|
169
|
+
}
|
|
170
|
+
async invoke(binding, d, input, ctx) {
|
|
171
|
+
const name = String(binding.config['tool'] ?? d.id);
|
|
172
|
+
const opts = {
|
|
173
|
+
signal: ctx.signal,
|
|
174
|
+
...(ctx.credential !== undefined ? { credential: ctx.credential } : {}),
|
|
175
|
+
};
|
|
176
|
+
const pinned = binding.config['schemaDigest'];
|
|
177
|
+
if (typeof pinned === 'string') {
|
|
178
|
+
const now = await this.current(name, opts);
|
|
179
|
+
if (now !== pinned) {
|
|
180
|
+
// The listing may be stale: look once more before refusing.
|
|
181
|
+
this.listed = undefined;
|
|
182
|
+
if ((await this.current(name, opts)) !== pinned)
|
|
183
|
+
throw new AgentropyError('IncompatibleVersion', `The MCP server's schema for ${d.id} changed since it was registered`, { details: { kind: 'tool', protocol: 'mcp' } });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const res = await this.client.callTool(name, input, opts);
|
|
187
|
+
if (res.isError === true)
|
|
188
|
+
throw unavailable('The MCP tool reported an error');
|
|
189
|
+
if (res.structuredContent !== undefined)
|
|
190
|
+
return res.structuredContent;
|
|
191
|
+
return {
|
|
192
|
+
text: (res.content ?? [])
|
|
193
|
+
.filter((c) => c.type === 'text' && typeof c.text === 'string')
|
|
194
|
+
.map((c) => c.text)
|
|
195
|
+
.join('\n'),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Streamable HTTP transport (MCP 2025-06-18): every message is a POST to one endpoint; a reply is JSON or an SSE
|
|
201
|
+
* stream that carries the response; the session ID the server issues at `initialize` is sent on later requests.
|
|
202
|
+
* A credential `{ token }` becomes a Bearer header. Redirects are never followed and replies are size-bounded.
|
|
203
|
+
*/
|
|
204
|
+
export function mcpHttpTransport(o) {
|
|
205
|
+
let seq = 0;
|
|
206
|
+
let session;
|
|
207
|
+
const send = async (message, opts) => {
|
|
208
|
+
const headers = {
|
|
209
|
+
'content-type': 'application/json',
|
|
210
|
+
accept: 'application/json, text/event-stream',
|
|
211
|
+
'mcp-protocol-version': MCP_PROTOCOL_VERSION,
|
|
212
|
+
...o.headers,
|
|
213
|
+
};
|
|
214
|
+
const sent = session;
|
|
215
|
+
if (sent)
|
|
216
|
+
headers['mcp-session-id'] = sent;
|
|
217
|
+
const token = opts.credential?.token;
|
|
218
|
+
if (typeof token === 'string')
|
|
219
|
+
headers['authorization'] = `Bearer ${token}`;
|
|
220
|
+
let res;
|
|
221
|
+
try {
|
|
222
|
+
res = await o.fetch(o.url, {
|
|
223
|
+
method: 'POST',
|
|
224
|
+
headers,
|
|
225
|
+
body: JSON.stringify({ jsonrpc: '2.0', ...message }),
|
|
226
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
227
|
+
redirect: 'manual',
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
if (err instanceof AgentropyError)
|
|
232
|
+
throw err;
|
|
233
|
+
throw unavailable('The MCP server is unreachable');
|
|
234
|
+
}
|
|
235
|
+
// An error reply is not read: release its body so the connection is not held until garbage collection (FIX-085).
|
|
236
|
+
if (res.status >= 300)
|
|
237
|
+
release(res.body);
|
|
238
|
+
if (res.status === 401 || res.status === 403)
|
|
239
|
+
throw new AgentropyError('AuthorityExpired', 'The MCP server rejected our credential', { details: { kind: 'credential', status: 'expired' } });
|
|
240
|
+
// The server does not know this session (it restarted or dropped it): forget it, so the client can start a new
|
|
241
|
+
// one (MCP 2025-06-18, session management).
|
|
242
|
+
if (res.status === 404 && sent) {
|
|
243
|
+
if (session === sent)
|
|
244
|
+
session = undefined;
|
|
245
|
+
throw unavailable('The MCP session ended', {
|
|
246
|
+
status: 404,
|
|
247
|
+
sessionLost: true,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
if (res.status >= 300)
|
|
251
|
+
throw unavailable('The MCP server refused the request', {
|
|
252
|
+
status: res.status,
|
|
253
|
+
});
|
|
254
|
+
return res;
|
|
255
|
+
};
|
|
256
|
+
return {
|
|
257
|
+
async request(method, params, opts) {
|
|
258
|
+
const id = ++seq;
|
|
259
|
+
const res = await send({ id, method, params }, opts);
|
|
260
|
+
const sid = res.headers.get('mcp-session-id');
|
|
261
|
+
if (method === 'initialize' && sid)
|
|
262
|
+
session = sid;
|
|
263
|
+
let text;
|
|
264
|
+
try {
|
|
265
|
+
text = await readBoundedText(res, o.maxResponseBytes ?? 1 << 20, opts.signal);
|
|
266
|
+
}
|
|
267
|
+
catch (err) {
|
|
268
|
+
throw unavailable(err instanceof ReplyTooLarge
|
|
269
|
+
? 'The MCP reply is too large'
|
|
270
|
+
: 'The MCP reply could not be read');
|
|
271
|
+
}
|
|
272
|
+
const messages = [];
|
|
273
|
+
if ((res.headers.get('content-type') ?? '').includes('text/event-stream')) {
|
|
274
|
+
for await (const data of sseData((async function* () {
|
|
275
|
+
yield text;
|
|
276
|
+
})())) {
|
|
277
|
+
try {
|
|
278
|
+
messages.push(JSON.parse(data));
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
/* a malformed event is skipped */
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
try {
|
|
287
|
+
messages.push(JSON.parse(text));
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
throw unavailable('Malformed MCP reply');
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const reply = messages.flat().find((m) => m?.id === id);
|
|
294
|
+
if (!reply)
|
|
295
|
+
throw unavailable('No MCP reply for the request');
|
|
296
|
+
if (reply.error)
|
|
297
|
+
throw unavailable('The MCP server returned an error', {
|
|
298
|
+
remoteCode: reply.error.code ?? null,
|
|
299
|
+
});
|
|
300
|
+
return reply.result;
|
|
301
|
+
},
|
|
302
|
+
async notify(method, params, opts) {
|
|
303
|
+
const res = await send({ method, params }, opts);
|
|
304
|
+
// A notification has no reply (202, no body): whatever the server sends anyway is not read (FIX-085).
|
|
305
|
+
release(res.body);
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|
package/dist/memory.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reference `memory` capability provider (FEAT-045; Capability v1 revision 14, "Memory provider"): `remember` and
|
|
3
|
+
* `recall` on the Store port.
|
|
4
|
+
*
|
|
5
|
+
* - **Scoped.** An entry belongs to a tenant and to the acting principal of the invocation (an agent's instance
|
|
6
|
+
* identity), so another tenant, or another agent in the same tenant, never reads or overwrites it.
|
|
7
|
+
* - **Bounded.** Key, text (8 KiB), tags, TTL and the number of live entries per scope (`maxEntries`, default 1,000)
|
|
8
|
+
* are validated; recall returns at most 20 entries.
|
|
9
|
+
* - **Retained.** An entry expires after its TTL (or the provider's `defaultTtlMs`); it is invisible at once and
|
|
10
|
+
* `compact()` removes it. There is no `forget` operation in v1.
|
|
11
|
+
* - **Plain matching.** Key, tag and a case-insensitive substring of the text: deterministic, newest first. A semantic
|
|
12
|
+
* provider is a different provider of the same capability. Recalled text is data written by earlier tasks and may
|
|
13
|
+
* carry instructions aimed at a model: callers treat it as untrusted.
|
|
14
|
+
*/
|
|
15
|
+
import { type CapabilityInvocationContext, type Store } from '@agentropy/core';
|
|
16
|
+
export interface MemoryOptions {
|
|
17
|
+
/** Live entries per tenant and principal (default 1,000); a new key beyond it is `QuotaExceeded`. */
|
|
18
|
+
maxEntries?: number;
|
|
19
|
+
/** TTL for entries that give none, in milliseconds (default: durable). */
|
|
20
|
+
defaultTtlMs?: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function memoryOperationHandlers(o: MemoryOptions & {
|
|
23
|
+
store: Store;
|
|
24
|
+
now: () => string;
|
|
25
|
+
}): Record<string, (input: unknown, ctx: CapabilityInvocationContext) => Promise<unknown>>;
|