@segmentstream/ontology 0.96.0 → 0.97.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.
@@ -1,7 +1,7 @@
1
1
  import type { ActionRuntime } from "../runtime-source.js";
2
2
  import { Effect, Schema } from "effect";
3
3
  import type { HttpServerRequest } from "effect/unstable/http";
4
- import { PermissionDenied } from "../errors.js";
4
+ import { ActionRejected, PermissionDenied } from "../errors.js";
5
5
  import { type ScopedPermission } from "../permissions.js";
6
6
  import { type Query, type QueryResult } from "../query.js";
7
7
  import { InvalidQuery } from "../runtime/errors.js";
@@ -163,6 +163,8 @@ export declare function makeOperations(backend: Backend, plan: ApiPlan, hooks: R
163
163
  };
164
164
  }[];
165
165
  }, import("../errors.js").ActionError | import("../connection.js").ConnectionError | import("../runtime/errors.js").WorkflowRecoveryUnavailable | import("../runtime/errors.js").TriggerInputInvalid | InvalidActionInput, RequestId | CurrentPrincipal>;
166
+ /** Calls a toolset's provider tool as the caller, through the toolset's connection. */
167
+ runToolsetTool: (toolset: import("../toolset.js").ResolvedToolset, tool: import("../toolset.js").ResolvedTool, call: import("./toolsets.js").ToolsetCall) => Effect.Effect<import("./toolsets.js").ToolResult, ActionRejected | PermissionDenied | import("../connection.js").ConnectionError, RequestId | CurrentPrincipal>;
166
168
  /** The caller's user, roles and permissions. It needs no permission. */
167
169
  caller: Effect.Effect<Caller, never, CurrentPrincipal>;
168
170
  };
@@ -18,6 +18,7 @@ import { ChatPostWire, RuntimeChatPostWire } from "./chat/schemas.js";
18
18
  import { OIDC_TOKEN_HEADER } from "./connections.js";
19
19
  import { InvalidActionInput, RequestId } from "./errors.js";
20
20
  import { recordReads } from "./record-reads.js";
21
+ import { runToolsetToolOf } from "./toolsets.js";
21
22
  import { AGENT_TASK_AUTHENTICATION } from "./agent/task-caller.js";
22
23
  /**
23
24
  * What the service does for a caller, whatever the transport: the reads and actions of every entity
@@ -386,6 +387,8 @@ export function makeOperations(backend, plan, hooks, connections, replicate, cha
386
387
  traverse: (planned, traversal, id, query) => traverseOf(reads, targets, planned, traversal, id, query),
387
388
  /** Runs an action as the caller, with the action's after-commit hook and connections. */
388
389
  runAction: runActionOf(backend, plan, hooks, connections, replicate, chatDelivery),
390
+ /** Calls a toolset's provider tool as the caller, through the toolset's connection. */
391
+ runToolsetTool: runToolsetToolOf(connections),
389
392
  /** The caller's user, roles and permissions. It needs no permission. */
390
393
  caller: callerOf(backend, plan.ontology),
391
394
  };
@@ -512,6 +512,37 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
512
512
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
513
513
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
514
514
  }>>>;
515
+ readonly toolsets: Schema.optionalKey<Schema.$Array<Schema.Struct<{
516
+ readonly name: Schema.String;
517
+ readonly description: Schema.String;
518
+ readonly connection: Schema.String;
519
+ readonly api: Schema.String;
520
+ readonly tools: Schema.$Array<Schema.Struct<{
521
+ readonly name: Schema.String;
522
+ readonly access: Schema.Literals<readonly ["read", "write"]>;
523
+ readonly fixed: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
524
+ }>>;
525
+ readonly actions: Schema.$Array<Schema.Struct<{
526
+ readonly name: Schema.String;
527
+ readonly description: Schema.String;
528
+ readonly permission: Schema.optionalKey<Schema.String>;
529
+ readonly input: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
530
+ readonly retryOnDeadlock: Schema.optionalKey<Schema.Boolean>;
531
+ readonly writes: Schema.optionalKey<Schema.$Array<Schema.String>>;
532
+ readonly connections: Schema.optionalKey<Schema.$Array<Schema.String>>;
533
+ readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
534
+ readonly entity: Schema.String;
535
+ readonly property: Schema.String;
536
+ }>>>;
537
+ readonly hints: Schema.optionalKey<Schema.Struct<{
538
+ readonly readOnly: Schema.optionalKey<Schema.Boolean>;
539
+ readonly connectionsReadOnly: Schema.optionalKey<Schema.Boolean>;
540
+ readonly destructive: Schema.optionalKey<Schema.Boolean>;
541
+ readonly irreversible: Schema.optionalKey<Schema.Boolean>;
542
+ readonly idempotent: Schema.optionalKey<Schema.Boolean>;
543
+ }>>;
544
+ }>>;
545
+ }>>>;
515
546
  }>, Schema.Struct<{
516
547
  readonly entities: Schema.toEncoded<Schema.$Array<Schema.encodeKeys<Schema.Struct<{
517
548
  readonly metrics: Schema.optionalKey<Schema.$Array<Schema.encodeKeys<Schema.Struct<{
@@ -753,6 +784,37 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
753
784
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
754
785
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
755
786
  }>>>>;
787
+ readonly toolsets: Schema.toEncoded<Schema.optionalKey<Schema.$Array<Schema.Struct<{
788
+ readonly name: Schema.String;
789
+ readonly description: Schema.String;
790
+ readonly connection: Schema.String;
791
+ readonly api: Schema.String;
792
+ readonly tools: Schema.$Array<Schema.Struct<{
793
+ readonly name: Schema.String;
794
+ readonly access: Schema.Literals<readonly ["read", "write"]>;
795
+ readonly fixed: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
796
+ }>>;
797
+ readonly actions: Schema.$Array<Schema.Struct<{
798
+ readonly name: Schema.String;
799
+ readonly description: Schema.String;
800
+ readonly permission: Schema.optionalKey<Schema.String>;
801
+ readonly input: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
802
+ readonly retryOnDeadlock: Schema.optionalKey<Schema.Boolean>;
803
+ readonly writes: Schema.optionalKey<Schema.$Array<Schema.String>>;
804
+ readonly connections: Schema.optionalKey<Schema.$Array<Schema.String>>;
805
+ readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
806
+ readonly entity: Schema.String;
807
+ readonly property: Schema.String;
808
+ }>>>;
809
+ readonly hints: Schema.optionalKey<Schema.Struct<{
810
+ readonly readOnly: Schema.optionalKey<Schema.Boolean>;
811
+ readonly connectionsReadOnly: Schema.optionalKey<Schema.Boolean>;
812
+ readonly destructive: Schema.optionalKey<Schema.Boolean>;
813
+ readonly irreversible: Schema.optionalKey<Schema.Boolean>;
814
+ readonly idempotent: Schema.optionalKey<Schema.Boolean>;
815
+ }>>;
816
+ }>>;
817
+ }>>>>;
756
818
  }>, never, never>;
757
819
  export declare const Graph: Schema.Struct<{
758
820
  readonly hash: Schema.String;
@@ -0,0 +1,49 @@
1
+ import { Effect } from "effect";
2
+ import { ConnectionError, type ConnectionTransport } from "../connection.js";
3
+ import { ActionRejected, PermissionDenied } from "../errors.js";
4
+ import type { ResolvedTool, ResolvedToolset } from "../toolset.js";
5
+ import { CurrentPrincipal } from "./authentication.js";
6
+ import { type CallerContext } from "./caller-context.js";
7
+ import type { ConnectionTransportFactory } from "./connections.js";
8
+ import { RequestId } from "./errors.js";
9
+ /** The MCP protocol version the service asks for; the server may answer with another it supports. */
10
+ export declare const MCP_PROTOCOL_VERSION = "2025-06-18";
11
+ /** The largest provider reply the service reads, under the agent's 8 MiB result-file limit. */
12
+ export declare const MAXIMUM_TOOL_REPLY_BYTES: number;
13
+ /** Forget every cached provider session; tests start from a cold instance. */
14
+ export declare function resetToolsetSessions(): void;
15
+ /** A provider's tool result, as MCP's `tools/call` answers it. */
16
+ export interface ToolResult {
17
+ readonly content: ReadonlyArray<Readonly<Record<string, unknown>>>;
18
+ readonly structuredContent?: Readonly<Record<string, unknown>>;
19
+ }
20
+ /** One toolset call, as the MCP server decoded it. */
21
+ export interface ToolsetCall {
22
+ /** The caller's arguments, without the confirmation presentation. */
23
+ readonly input: Readonly<Record<string, unknown>>;
24
+ /** The deployment's OIDC token, which authorizes the connection call. */
25
+ readonly identityToken: string | undefined;
26
+ }
27
+ /**
28
+ * The JSON-RPC response with `id` in a reply: the body itself for `application/json`, or the data
29
+ * of the server-sent event that carries it for `text/event-stream`.
30
+ */
31
+ export declare function rpcResponse(reply: {
32
+ readonly headers: ReadonlyArray<readonly [string, string]>;
33
+ readonly body: Uint8Array;
34
+ }, id: number): Readonly<Record<string, unknown>> | undefined;
35
+ /**
36
+ * Calls one tool of the toolset's MCP API through the connection proxy, reusing the instance's
37
+ * session and opening a new one once when the server no longer knows it.
38
+ */
39
+ export declare function callTool(transport: ConnectionTransport["Service"], toolset: ResolvedToolset, tool: ResolvedTool, args: Readonly<Record<string, unknown>>): Effect.Effect<ToolResult, ConnectionError | ActionRejected>;
40
+ /** Whether the caller is an OAuth client the member consented to reading only. */
41
+ export declare function isReadScoped(caller: CallerContext): boolean;
42
+ /** The text of a tool result for MCP clients that read `content`: the provider's text items. */
43
+ export declare function resultText(result: ToolResult): string;
44
+ /**
45
+ * Runs one toolset tool as the caller: the caller must hold `<toolset>:<tool>`; the workspace's
46
+ * fixed values replace whatever the caller sent for them; the call goes through the toolset's
47
+ * connection, audited as `<toolset>.<tool>`.
48
+ */
49
+ export declare function runToolsetToolOf(connections: ConnectionTransportFactory): (toolset: ResolvedToolset, tool: ResolvedTool, call: ToolsetCall) => Effect.Effect<ToolResult, ActionRejected | PermissionDenied | ConnectionError, RequestId | CurrentPrincipal>;
@@ -0,0 +1,284 @@
1
+ import { Effect } from "effect";
2
+ import { ConnectionError } from "../connection.js";
3
+ import { ActionRejected, PermissionDenied } from "../errors.js";
4
+ import { isAllowed } from "../permissions.js";
5
+ import { CurrentPrincipal } from "./authentication.js";
6
+ import { currentCaller } from "./caller-context.js";
7
+ import { READ_SCOPE } from "./oauth/protocol.js";
8
+ import { RequestId } from "./errors.js";
9
+ /** The MCP protocol version the service asks for; the server may answer with another it supports. */
10
+ export const MCP_PROTOCOL_VERSION = "2025-06-18";
11
+ /** The largest provider reply the service reads, under the agent's 8 MiB result-file limit. */
12
+ export const MAXIMUM_TOOL_REPLY_BYTES = 8 * 1024 * 1024;
13
+ /** How long a provider's MCP session is reused within one warm service instance. */
14
+ const SESSION_TTL_MS = 10 * 60 * 1000;
15
+ const encoder = new TextEncoder();
16
+ const decoder = new TextDecoder();
17
+ const sessions = new Map();
18
+ let lastRequestId = 0;
19
+ /**
20
+ * A JSON-RPC id no other request of this instance uses. Calls of different members share a
21
+ * connection's session, and a server routes each response by its request's id: two requests with
22
+ * one id could swap their results.
23
+ */
24
+ function nextRequestId() {
25
+ lastRequestId = lastRequestId >= Number.MAX_SAFE_INTEGER ? 1 : lastRequestId + 1;
26
+ return lastRequestId;
27
+ }
28
+ /** Forget every cached provider session; tests start from a cold instance. */
29
+ export function resetToolsetSessions() {
30
+ sessions.clear();
31
+ }
32
+ function header(reply, name) {
33
+ return reply.headers.find(([candidate]) => candidate.toLowerCase() === name)?.[1];
34
+ }
35
+ function failure(connection, reason, message, cause) {
36
+ return new ConnectionError({
37
+ connection,
38
+ reason,
39
+ message,
40
+ retryable: reason === "unavailable" || reason === "timeout",
41
+ ...(cause === undefined ? {} : { cause }),
42
+ });
43
+ }
44
+ /** The longest part of a provider's reply kept in an operator diagnostic. */
45
+ const DIAGNOSTIC_REPLY_CHARS = 2000;
46
+ /**
47
+ * What the provider answered, for operator diagnostics only: its status, its JSON-RPC error when it
48
+ * sent one, and the start of its body. The proxy already refuses replies that echo a credential.
49
+ */
50
+ function providerAnswer(reply, error) {
51
+ const body = decoder.decode(reply.body).slice(0, DIAGNOSTIC_REPLY_CHARS);
52
+ return new Error(`MCP server answered ${reply.status}` +
53
+ (error === undefined ? "" : `; JSON-RPC error ${JSON.stringify(error)}`) +
54
+ (body === "" ? "" : `; body: ${body}`));
55
+ }
56
+ function isObject(value) {
57
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58
+ }
59
+ /** Sends one JSON-RPC message to the MCP API and reads the whole reply, bounded. */
60
+ function send(transport, toolset, message, session) {
61
+ const call = {
62
+ connection: toolset.connection,
63
+ api: toolset.api,
64
+ method: "POST",
65
+ path: "/",
66
+ headers: [
67
+ ["content-type", "application/json"],
68
+ ["accept", "application/json, text/event-stream"],
69
+ ...(session === undefined
70
+ ? []
71
+ : [["mcp-protocol-version", session.protocolVersion]]),
72
+ ...(session?.id === undefined ? [] : [["mcp-session-id", session.id]]),
73
+ ],
74
+ body: encoder.encode(JSON.stringify(message)),
75
+ };
76
+ // The service's buffered call collects a streamed reply, so the proxy's 2 MiB cap does not apply.
77
+ return transport
78
+ .request(call)
79
+ .pipe(Effect.flatMap((reply) => reply.body.byteLength > MAXIMUM_TOOL_REPLY_BYTES
80
+ ? Effect.fail(failure(toolset.connection, "invalid_response", "The tool's reply exceeds 8 MiB."))
81
+ : Effect.succeed(reply)));
82
+ }
83
+ /**
84
+ * The JSON-RPC response with `id` in a reply: the body itself for `application/json`, or the data
85
+ * of the server-sent event that carries it for `text/event-stream`.
86
+ */
87
+ export function rpcResponse(reply, id) {
88
+ const type = (header(reply, "content-type") ?? "").toLowerCase();
89
+ const text = decoder.decode(reply.body);
90
+ const candidates = [];
91
+ if (type.includes("text/event-stream")) {
92
+ for (const event of text.split(/\r?\n\r?\n/)) {
93
+ const data = event
94
+ .split(/\r?\n/)
95
+ .filter((line) => line.startsWith("data:"))
96
+ .map((line) => line.slice(5).replace(/^ /, ""))
97
+ .join("\n");
98
+ if (data !== "") {
99
+ try {
100
+ candidates.push(JSON.parse(data));
101
+ }
102
+ catch {
103
+ // A malformed event is skipped; the matching response is required below.
104
+ }
105
+ }
106
+ }
107
+ }
108
+ else {
109
+ try {
110
+ candidates.push(JSON.parse(text));
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ }
116
+ return candidates.find((candidate) => isObject(candidate) && candidate.id === id);
117
+ }
118
+ function statusFailure(toolset, reply) {
119
+ // Throttling passes: the caller may retry, after the delay the provider names.
120
+ const retryAfter = reply.status === 429 ? header(reply, "retry-after") : undefined;
121
+ return failure(toolset.connection, reply.status >= 500 || reply.status === 429 ? "unavailable" : "refused", `The MCP server of ${toolset.connection}'s ${toolset.api} API answered ${reply.status}` +
122
+ (retryAfter === undefined ? "." : `; retry after ${retryAfter}.`), providerAnswer(reply));
123
+ }
124
+ /** Logs a provider's refusal of a tool call for operators, with what it answered. */
125
+ function refusalLog(toolset, tool, cause) {
126
+ return Effect.logWarning("ontology.toolset.refused", cause).pipe(Effect.annotateLogs({ toolset: toolset.name, tool: tool.name }));
127
+ }
128
+ /** Opens a session: `initialize`, then the `notifications/initialized` notification. */
129
+ function initialize(transport, toolset) {
130
+ return Effect.gen(function* () {
131
+ const id = nextRequestId();
132
+ const reply = yield* send(transport, toolset, {
133
+ jsonrpc: "2.0",
134
+ id,
135
+ method: "initialize",
136
+ params: {
137
+ protocolVersion: toolset.protocolVersion || MCP_PROTOCOL_VERSION,
138
+ capabilities: {},
139
+ clientInfo: { name: "segmentstream", version: "1" },
140
+ },
141
+ }, undefined);
142
+ if (reply.status < 200 || reply.status >= 300) {
143
+ return yield* statusFailure(toolset, reply);
144
+ }
145
+ const response = rpcResponse(reply, id);
146
+ const result = isObject(response?.result) ? response.result : undefined;
147
+ if (result === undefined) {
148
+ return yield* failure(toolset.connection, "invalid_response", `The MCP server of ${toolset.connection}'s ${toolset.api} API did not initialize a session.`, providerAnswer(reply, response?.error));
149
+ }
150
+ const session = {
151
+ id: header(reply, "mcp-session-id"),
152
+ protocolVersion: typeof result.protocolVersion === "string" ? result.protocolVersion : MCP_PROTOCOL_VERSION,
153
+ expiresAt: Date.now() + SESSION_TTL_MS,
154
+ };
155
+ const initialized = yield* send(transport, toolset, { jsonrpc: "2.0", method: "notifications/initialized" }, session);
156
+ // A session the server did not accept as initialized is not returned, so it is never reused.
157
+ if (initialized.status < 200 || initialized.status >= 300) {
158
+ return yield* statusFailure(toolset, initialized);
159
+ }
160
+ return session;
161
+ });
162
+ }
163
+ /**
164
+ * Calls one tool of the toolset's MCP API through the connection proxy, reusing the instance's
165
+ * session and opening a new one once when the server no longer knows it.
166
+ */
167
+ export function callTool(transport, toolset, tool, args) {
168
+ const key = `${toolset.connection}\u0000${toolset.api}`;
169
+ return Effect.gen(function* () {
170
+ // A new id for each attempt, so that no request of another call can share it.
171
+ const message = () => ({
172
+ jsonrpc: "2.0",
173
+ id: nextRequestId(),
174
+ method: "tools/call",
175
+ params: { name: tool.name, arguments: args },
176
+ });
177
+ const cached = sessions.get(key);
178
+ let session = cached !== undefined && cached.expiresAt > Date.now()
179
+ ? cached
180
+ : yield* initialize(transport, toolset);
181
+ sessions.set(key, session);
182
+ let request = message();
183
+ let reply = yield* send(transport, toolset, request, session);
184
+ // A server that forgot the session answers 404; a fresh one is opened once.
185
+ if (reply.status === 404 && cached !== undefined && session === cached) {
186
+ sessions.delete(key);
187
+ session = yield* initialize(transport, toolset);
188
+ sessions.set(key, session);
189
+ request = message();
190
+ reply = yield* send(transport, toolset, request, session);
191
+ }
192
+ if (reply.status < 200 || reply.status >= 300) {
193
+ // The next call opens a fresh session instead of reusing one the server may not honour.
194
+ sessions.delete(key);
195
+ return yield* statusFailure(toolset, reply);
196
+ }
197
+ const response = rpcResponse(reply, request.id);
198
+ if (response === undefined) {
199
+ return yield* failure(toolset.connection, "invalid_response", `The MCP server of ${toolset.connection}'s ${toolset.api} API sent no answer to ${tool.name}.`, providerAnswer(reply));
200
+ }
201
+ if (isObject(response.error)) {
202
+ const detail = typeof response.error.message === "string" ? response.error.message : "";
203
+ const cause = providerAnswer(reply, response.error);
204
+ // A refusal is an expected answer, so the service would not log it: operators keep the
205
+ // provider's code, message and data here.
206
+ yield* refusalLog(toolset, tool, cause);
207
+ return yield* new ActionRejected({
208
+ message: `${toolset.name}_${tool.name} was refused by the provider${detail === "" ? "." : `: ${detail}`}`,
209
+ cause,
210
+ });
211
+ }
212
+ const result = isObject(response.result) ? response.result : {};
213
+ const content = Array.isArray(result.content)
214
+ ? result.content.filter((item) => isObject(item))
215
+ : [];
216
+ if (result.isError === true) {
217
+ const detail = content
218
+ .map((item) => (typeof item.text === "string" ? item.text : ""))
219
+ .filter((text) => text !== "")
220
+ .join("\n");
221
+ const cause = providerAnswer(reply);
222
+ yield* refusalLog(toolset, tool, cause);
223
+ return yield* new ActionRejected({
224
+ message: `${toolset.name}_${tool.name} failed at the provider${detail === "" ? "." : `: ${detail}`}`,
225
+ cause,
226
+ });
227
+ }
228
+ return {
229
+ content,
230
+ ...(isObject(result.structuredContent)
231
+ ? { structuredContent: result.structuredContent }
232
+ : {}),
233
+ };
234
+ });
235
+ }
236
+ /** Whether the caller is an OAuth client the member consented to reading only. */
237
+ export function isReadScoped(caller) {
238
+ return caller.kind === "oauth" && caller.scope === READ_SCOPE;
239
+ }
240
+ /** The text of a tool result for MCP clients that read `content`: the provider's text items. */
241
+ export function resultText(result) {
242
+ const texts = result.content.flatMap((item) => {
243
+ if (item.type === "text" && typeof item.text === "string") {
244
+ return [item.text];
245
+ }
246
+ if (item.type === "resource" &&
247
+ isObject(item.resource) &&
248
+ typeof item.resource.text === "string") {
249
+ return [item.resource.text];
250
+ }
251
+ return [];
252
+ });
253
+ return texts.length > 0 ? texts.join("\n\n") : JSON.stringify(result.structuredContent ?? {});
254
+ }
255
+ /**
256
+ * Runs one toolset tool as the caller: the caller must hold `<toolset>:<tool>`; the workspace's
257
+ * fixed values replace whatever the caller sent for them; the call goes through the toolset's
258
+ * connection, audited as `<toolset>.<tool>`.
259
+ */
260
+ export function runToolsetToolOf(connections) {
261
+ return (toolset, tool, call) => Effect.gen(function* () {
262
+ const principal = yield* CurrentPrincipal;
263
+ const caller = yield* currentCaller;
264
+ // Consent to reading the ontology is no consent to calling a provider.
265
+ if (isReadScoped(caller)) {
266
+ return yield* new PermissionDenied({
267
+ message: `${tool.mcpName} is not available to a client consented to ${READ_SCOPE}.`,
268
+ permission: tool.permission,
269
+ });
270
+ }
271
+ if (!isAllowed(tool.permission, principal)) {
272
+ return yield* new PermissionDenied({
273
+ message: `Calling ${tool.mcpName} requires ${tool.permission}.`,
274
+ permission: tool.permission,
275
+ });
276
+ }
277
+ const requestId = yield* RequestId;
278
+ const transport = connections({
279
+ identityToken: call.identityToken,
280
+ audit: { action: `${toolset.name}.${tool.name}`, principalId: principal.id, requestId },
281
+ });
282
+ return yield* callTool(transport, toolset, tool, { ...call.input, ...tool.fixed });
283
+ });
284
+ }
@@ -0,0 +1,141 @@
1
+ import { Schema } from "effect";
2
+ import type { AnyConnectionHandle } from "./connection.js";
3
+ export declare const ToolsetTypeId: unique symbol;
4
+ /** The lock format `segmentstream connection mcp lock` writes. */
5
+ export declare const TOOLSET_LOCK_VERSION = 1;
6
+ /**
7
+ * A tool name an MCP API may declare: lowercase snake_case of at most 64 characters, so that
8
+ * `<toolset>:<tool>` is an ontology permission and `<toolset>_<tool>` an MCP tool name.
9
+ */
10
+ export declare const MCP_TOOL_NAME: RegExp;
11
+ /** The most tools one MCP API may declare, as `connections/connections.py` enforces. */
12
+ export declare const MAXIMUM_TOOLSET_TOOLS = 100;
13
+ /** A value the workspace fixes for one argument of a tool. */
14
+ export declare const FixedValue: Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>;
15
+ export type FixedValue = typeof FixedValue.Type;
16
+ /** One locked tool: the declared access and fixed values, and what the server said about it. */
17
+ export declare const ToolsetLockTool: Schema.Struct<{
18
+ readonly name: Schema.String;
19
+ readonly access: Schema.Literals<readonly ["read", "write"]>;
20
+ readonly fixed: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
21
+ readonly description: Schema.String;
22
+ readonly inputSchema: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
23
+ readonly outputSchema: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
24
+ readonly annotations: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
25
+ }>;
26
+ export type ToolsetLockTool = typeof ToolsetLockTool.Type;
27
+ /**
28
+ * The pinned tools of one MCP API of a connection, written by `segmentstream connection mcp lock`
29
+ * and committed with the workspace. The ontology's catalog is built from it, so a provider's
30
+ * change reaches members only through a reviewed commit and a deploy.
31
+ */
32
+ export declare const ToolsetLock: Schema.Struct<{
33
+ readonly version: Schema.Literal<1>;
34
+ readonly connection: Schema.String;
35
+ readonly api: Schema.String;
36
+ readonly url: Schema.String;
37
+ readonly protocolVersion: Schema.String;
38
+ readonly server: Schema.optionalKey<Schema.Struct<{
39
+ readonly name: Schema.String;
40
+ readonly version: Schema.optionalKey<Schema.String>;
41
+ }>>;
42
+ readonly tools: Schema.$Array<Schema.Struct<{
43
+ readonly name: Schema.String;
44
+ readonly access: Schema.Literals<readonly ["read", "write"]>;
45
+ readonly fixed: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
46
+ readonly description: Schema.String;
47
+ readonly inputSchema: Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>;
48
+ readonly outputSchema: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
49
+ readonly annotations: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
50
+ }>>;
51
+ }>;
52
+ export type ToolsetLock = typeof ToolsetLock.Type;
53
+ /** The workspace's own words for one tool, replacing the provider's. */
54
+ export interface ToolsetToolOptions {
55
+ readonly description?: string;
56
+ }
57
+ export interface ToolsetDefinition {
58
+ /** The connection whose MCP API serves the tools, listed in `defineOntology({ connections })`. */
59
+ readonly connection: AnyConnectionHandle;
60
+ /** The name of the connection's MCP API in `connections/connections.py`. */
61
+ readonly api: string;
62
+ /** The content of the lock file `ontology/mcp/<key>.<api>.lock.json`, imported as JSON. */
63
+ readonly lock: unknown;
64
+ /** What the toolset is for, in the workspace's words; agents read it to choose a tool. */
65
+ readonly description: string;
66
+ /** Per-tool overrides, by the provider's tool name. */
67
+ readonly tools?: Readonly<Record<string, ToolsetToolOptions>>;
68
+ }
69
+ /** A provider's MCP tools served by the ontology: see {@link toolset}. */
70
+ export interface Toolset<Name extends string = string> {
71
+ readonly [ToolsetTypeId]: typeof ToolsetTypeId;
72
+ readonly name: Name;
73
+ readonly definition: ToolsetDefinition;
74
+ }
75
+ /**
76
+ * Serves the tools a connection's MCP API declares, as `connections/connections.py` lists them and
77
+ * the lock pins them, to every client of the ontology's MCP server. Each tool becomes the MCP tool
78
+ * `<toolset>_<tool>`, which a member may see and call with the permission `<toolset>:<tool>`. A
79
+ * toolset has no records: no table, `find`, `get` or `history`.
80
+ *
81
+ * `lock` is the JSON of `ontology/mcp/<key>.<api>.lock.json`, imported with `{ type: "json" }`:
82
+ *
83
+ * ```ts
84
+ * export const GitHub = toolset("github", {
85
+ * connection: github,
86
+ * api: "mcp",
87
+ * lock: githubLock,
88
+ * description: "The platform's source repository: code, commits, pull requests and issues.",
89
+ * });
90
+ * ```
91
+ */
92
+ export declare function toolset<const Name extends string>(name: Name, definition: ToolsetDefinition): Toolset<Name>;
93
+ export declare function isToolset(value: unknown): value is Toolset;
94
+ /** How a tool behaves, from the workspace's declared access and the provider's hints. */
95
+ export interface ResolvedToolHints {
96
+ readonly readOnly: boolean;
97
+ readonly destructive: boolean;
98
+ readonly idempotent: boolean;
99
+ }
100
+ /** One tool of a checked toolset, as the service serves it. */
101
+ export interface ResolvedTool {
102
+ /** The provider's tool name. */
103
+ readonly name: string;
104
+ /** `<toolset>_<tool>`. */
105
+ readonly mcpName: string;
106
+ /** `<toolset>:<tool>`. */
107
+ readonly permission: string;
108
+ readonly access: "read" | "write";
109
+ readonly fixed: Readonly<Record<string, FixedValue>>;
110
+ readonly description: string;
111
+ /** The locked input schema without the fixed arguments, which callers never send. */
112
+ readonly inputSchema: Readonly<Record<string, unknown>>;
113
+ readonly hints: ResolvedToolHints;
114
+ }
115
+ /** A checked toolset. */
116
+ export interface ResolvedToolset {
117
+ /** The wire name. */
118
+ readonly name: string;
119
+ readonly description: string;
120
+ readonly connection: string;
121
+ readonly api: string;
122
+ readonly protocolVersion: string;
123
+ readonly tools: ReadonlyArray<ResolvedTool>;
124
+ }
125
+ /** The root keyword that composes subschemas in a tool's input, if any. */
126
+ export declare function composingKeyword(schema: Readonly<Record<string, unknown>>): string | undefined;
127
+ /**
128
+ * The root keyword that keeps the service from changing a tool's input, if any: fixed values are
129
+ * removed from it, and a tool that is not a read gains the confirmation argument.
130
+ */
131
+ export declare function fixedArgumentsConflict(schema: Readonly<Record<string, unknown>>, fixed: Readonly<Record<string, unknown>>, access?: "read" | "write"): string | undefined;
132
+ /**
133
+ * A tool's input schema without its fixed arguments: they are removed from `properties`,
134
+ * `required` and `dependentRequired`, and `minProperties` and `maxProperties` no longer count the
135
+ * ones the schema declares, so a caller cannot send or even see them and the remaining input is
136
+ * satisfiable; the service adds their values to each call. `check` refuses a schema whose other
137
+ * root keywords a fixed value could break ({@link fixedArgumentsConflict}).
138
+ */
139
+ export declare function withoutFixedArguments(schema: Readonly<Record<string, unknown>>, fixed: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>>;
140
+ /** The workspace's access and the provider's annotations, as the service's tool hints. */
141
+ export declare function toolHints(access: "read" | "write", annotations: Readonly<Record<string, unknown>> | undefined): ResolvedToolHints;