@segmentstream/ontology 0.96.0 → 0.98.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/README.md +15 -3
- package/dist/agent-review.d.ts +95 -0
- package/dist/agent-review.js +200 -0
- package/dist/analyze.d.ts +10 -2
- package/dist/analyze.js +240 -19
- package/dist/bin/check.js +2 -0
- package/dist/chat.d.ts +16 -0
- package/dist/diagnostics.d.ts +3 -3
- package/dist/diagnostics.js +2 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/manifest.d.ts +505 -2
- package/dist/manifest.js +55 -2
- package/dist/migrate/model.d.ts +272 -0
- package/dist/ontology.d.ts +3 -0
- package/dist/ontology.js +1 -0
- package/dist/permissions.d.ts +5 -3
- package/dist/permissions.js +9 -5
- package/dist/runtime/agents.js +53 -0
- package/dist/service/agent/protocol.d.ts +18 -0
- package/dist/service/agent/protocol.js +33 -0
- package/dist/service/agent/server.js +48 -1
- package/dist/service/catalog.js +10 -1
- package/dist/service/chat/archive.d.ts +2 -1
- package/dist/service/chat/delivery.js +11 -0
- package/dist/service/chat/envelope.d.ts +16 -16
- package/dist/service/chat/providers/provider.d.ts +2 -0
- package/dist/service/chat/providers/slack.js +1 -1
- package/dist/service/chat/providers/telegram.d.ts +6 -1
- package/dist/service/chat/providers/telegram.js +14 -3
- package/dist/service/chat/providers/whatsapp.js +1 -1
- package/dist/service/chat/review-delivery.d.ts +38 -0
- package/dist/service/chat/review-delivery.js +258 -0
- package/dist/service/connections.js +1 -0
- package/dist/service/discovery-search.d.ts +1 -1
- package/dist/service/mcp/runtime-policy.js +5 -1
- package/dist/service/mcp/server.js +13 -1
- package/dist/service/mcp/tools.d.ts +5 -0
- package/dist/service/mcp/tools.js +30 -0
- package/dist/service/operations.d.ts +3 -1
- package/dist/service/operations.js +16 -1
- package/dist/service/runtime-contract.d.ts +28 -0
- package/dist/service/schemas.d.ts +62 -0
- package/dist/service/toolsets.d.ts +49 -0
- package/dist/service/toolsets.js +284 -0
- package/dist/slack.js +3 -1
- package/dist/toolset.d.ts +141 -0
- package/dist/toolset.js +154 -0
- package/dist/whatsapp.js +3 -1
- package/package.json +1 -1
|
@@ -6,6 +6,7 @@ import type { BuiltApi } from "../api.js";
|
|
|
6
6
|
import type { CallerContext } from "../caller-context.js";
|
|
7
7
|
import { type ConfirmationFacts } from "./confirmation.js";
|
|
8
8
|
import type { PlannedAction, PlannedEntity } from "../plan.js";
|
|
9
|
+
import type { ResolvedTool, ResolvedToolset } from "../../toolset.js";
|
|
9
10
|
/** How a tool behaves, as MCP's tool annotations say it. */
|
|
10
11
|
export interface McpToolAnnotations {
|
|
11
12
|
readonly readOnlyHint: boolean;
|
|
@@ -41,6 +42,10 @@ export type McpToolTarget = {
|
|
|
41
42
|
} | {
|
|
42
43
|
readonly kind: "member-file";
|
|
43
44
|
readonly operation: MemberFileOperation;
|
|
45
|
+
} | {
|
|
46
|
+
readonly kind: "toolset";
|
|
47
|
+
readonly toolset: ResolvedToolset;
|
|
48
|
+
readonly tool: ResolvedTool;
|
|
44
49
|
};
|
|
45
50
|
/** A tool of the ontology's MCP server, derived from the same plan as the HTTP routes. */
|
|
46
51
|
export interface McpTool {
|
|
@@ -17,6 +17,7 @@ import { ChatPostResult } from "../../chat.js";
|
|
|
17
17
|
import { actionDescription, requires } from "../descriptions.js";
|
|
18
18
|
import { DiscoverInput, DiscoverToolOutput } from "../discovery-schemas.js";
|
|
19
19
|
import { DIMENSIONS_LIMIT, hasMetrics, VALUES_DEFAULT, VALUES_LIMIT } from "./metric-tools.js";
|
|
20
|
+
import { isReadScoped } from "../toolsets.js";
|
|
20
21
|
import { NavigationInput, NavigationToolOutput } from "../navigation-schemas.js";
|
|
21
22
|
import { METRIC_QUERY_FILTER_OPERATORS, METRIC_QUERY_GRANULARITIES, METRIC_QUERY_LIMITS, METRIC_QUERY_PERIOD_UNITS, METRIC_QUERY_PERIODS, HistoryPage, MAXIMUM_TIMEZONE_LENGTH, Me, } from "../schemas.js";
|
|
22
23
|
const DEFS = "#/$defs/";
|
|
@@ -315,6 +316,31 @@ function actionTool(planned, plannedAction) {
|
|
|
315
316
|
target: { kind: "action", planned, action: plannedAction },
|
|
316
317
|
};
|
|
317
318
|
}
|
|
319
|
+
/**
|
|
320
|
+
* A provider's tool, as a toolset serves it: the workspace declares whether it only reads, so a
|
|
321
|
+
* read tool never needs confirmation and every other tool is external and is confirmed.
|
|
322
|
+
*/
|
|
323
|
+
function toolsetTool(toolset, tool) {
|
|
324
|
+
const schema = tool.inputSchema;
|
|
325
|
+
// A write tool is confirmed, so its calls carry the confirmation argument too.
|
|
326
|
+
const inputSchema = !tool.hints.readOnly && typeof schema.maxProperties === "number"
|
|
327
|
+
? { ...schema, maxProperties: schema.maxProperties + 1 }
|
|
328
|
+
: schema;
|
|
329
|
+
return {
|
|
330
|
+
name: tool.mcpName,
|
|
331
|
+
title: `${humanize(toolset.name)}: ${humanize(tool.name).toLowerCase()}`,
|
|
332
|
+
description: `${tool.description}\n\n${toolset.description}`,
|
|
333
|
+
inputSchema,
|
|
334
|
+
annotations: {
|
|
335
|
+
readOnlyHint: tool.hints.readOnly,
|
|
336
|
+
destructiveHint: tool.hints.destructive,
|
|
337
|
+
idempotentHint: tool.hints.idempotent,
|
|
338
|
+
openWorldHint: true,
|
|
339
|
+
},
|
|
340
|
+
permissions: [tool.permission],
|
|
341
|
+
target: { kind: "toolset", toolset, tool },
|
|
342
|
+
};
|
|
343
|
+
}
|
|
318
344
|
/** `discover` of an ontology that ranks entities by meaning with its decision model. */
|
|
319
345
|
const DISCOVER_BY_MEANING = "Find which entities a request concerns, ranked by meaning: pass as query the member's request " +
|
|
320
346
|
"in their words, and what you understand they want. Each match is an entity with its " +
|
|
@@ -719,6 +745,9 @@ export function mcpTools(built, conversations = false, storage = {}, navigation
|
|
|
719
745
|
}))
|
|
720
746
|
: [...reads, ...actions]));
|
|
721
747
|
}
|
|
748
|
+
for (const toolset of built.plan.ontology.toolsets ?? []) {
|
|
749
|
+
tools.push(...toolset.tools.map((tool) => toolsetTool(toolset, tool)));
|
|
750
|
+
}
|
|
722
751
|
const discover = tools.findIndex((tool) => tool.name === "discover");
|
|
723
752
|
// Word search duplicates the client's own tool search; ranking by meaning does not.
|
|
724
753
|
if (discover >= 0) {
|
|
@@ -920,6 +949,7 @@ export function mcpTools(built, conversations = false, storage = {}, navigation
|
|
|
920
949
|
export function visibleTools(tools, caller, provenance = { kind: "unverified" }) {
|
|
921
950
|
return tools.flatMap((tool) => {
|
|
922
951
|
if (!runtimeAllows(provenance, tool) ||
|
|
952
|
+
(tool.target.kind === "toolset" && isReadScoped(provenance)) ||
|
|
923
953
|
!tool.permissions.every((required) => isAllowed(required, caller))) {
|
|
924
954
|
return [];
|
|
925
955
|
}
|
|
@@ -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
|
|
@@ -240,8 +241,20 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
|
|
|
240
241
|
}
|
|
241
242
|
input = { ...values, idempotency_key: envelope.operation_id };
|
|
242
243
|
}
|
|
244
|
+
// Approving a held reply sends it to a person: a member, or the agent acting for one with
|
|
245
|
+
// their confirmation, decides; an agent task has no one to confirm it.
|
|
246
|
+
if (planned.name === "agent_review" &&
|
|
247
|
+
name === "approve" &&
|
|
248
|
+
principal.authenticatedVia === AGENT_TASK_AUTHENTICATION) {
|
|
249
|
+
return yield* new ActionRejected({
|
|
250
|
+
message: "Agent tasks cannot approve a held reply: agent_review.approve needs a member to " +
|
|
251
|
+
"confirm the text the person receives.",
|
|
252
|
+
});
|
|
253
|
+
}
|
|
243
254
|
const requestId = yield* RequestId;
|
|
244
|
-
const delivery = planned.name === "agent_chat" &&
|
|
255
|
+
const delivery = (planned.name === "agent_chat" &&
|
|
256
|
+
(name === "post_message" || name === "preview_message")) ||
|
|
257
|
+
(planned.name === "agent_review" && name === "approve")
|
|
245
258
|
? chatDelivery?.({
|
|
246
259
|
backend,
|
|
247
260
|
principal,
|
|
@@ -386,6 +399,8 @@ export function makeOperations(backend, plan, hooks, connections, replicate, cha
|
|
|
386
399
|
traverse: (planned, traversal, id, query) => traverseOf(reads, targets, planned, traversal, id, query),
|
|
387
400
|
/** Runs an action as the caller, with the action's after-commit hook and connections. */
|
|
388
401
|
runAction: runActionOf(backend, plan, hooks, connections, replicate, chatDelivery),
|
|
402
|
+
/** Calls a toolset's provider tool as the caller, through the toolset's connection. */
|
|
403
|
+
runToolsetTool: runToolsetToolOf(connections),
|
|
389
404
|
/** The caller's user, roles and permissions. It needs no permission. */
|
|
390
405
|
caller: callerOf(backend, plan.ontology),
|
|
391
406
|
};
|
|
@@ -380,6 +380,34 @@ export interface AgentStore {
|
|
|
380
380
|
readonly agentLeft?: true;
|
|
381
381
|
readonly migratedFrom?: string;
|
|
382
382
|
}) => Effect.Effect<SeenChat>;
|
|
383
|
+
/**
|
|
384
|
+
* A reply the agent held for review becomes a pending `agent_review` for the member it answers,
|
|
385
|
+
* once per `key`: a repeated report answers the review it created. `undefined` when the member is
|
|
386
|
+
* not an active member of the app. Absent on stores that predate reviews.
|
|
387
|
+
*/
|
|
388
|
+
readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
|
|
389
|
+
}
|
|
390
|
+
/** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
|
|
391
|
+
export interface HeldReplyInput {
|
|
392
|
+
readonly key: string;
|
|
393
|
+
readonly provider: string;
|
|
394
|
+
readonly chatId: string;
|
|
395
|
+
/** Whom the provider sends the reply to: the chat's id, or the person's id where it differs. */
|
|
396
|
+
readonly recipient: string;
|
|
397
|
+
readonly threadId: string;
|
|
398
|
+
readonly replyTo: string | null;
|
|
399
|
+
readonly memberId: string;
|
|
400
|
+
readonly sessionId: string;
|
|
401
|
+
readonly text: string;
|
|
402
|
+
readonly mode: "always" | "whenUnsure";
|
|
403
|
+
readonly confidence: number | null;
|
|
404
|
+
}
|
|
405
|
+
/** The review a held reply became. */
|
|
406
|
+
export interface HeldReview {
|
|
407
|
+
readonly id: string;
|
|
408
|
+
readonly status: string;
|
|
409
|
+
/** Whether this report created it, rather than finding the review an earlier one created. */
|
|
410
|
+
readonly created: boolean;
|
|
383
411
|
}
|
|
384
412
|
declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segmentstream/ontology/OntologyBackend", {
|
|
385
413
|
readonly workflowAdmissions?: {
|
|
@@ -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
|
+
}
|
package/dist/slack.js
CHANGED
|
@@ -17,5 +17,7 @@ export function escapeSlackMarkdown(text) {
|
|
|
17
17
|
* Markdown.
|
|
18
18
|
*/
|
|
19
19
|
export function renderSlack(markdown, attribution, separator = "\n\n") {
|
|
20
|
-
return
|
|
20
|
+
return attribution === ""
|
|
21
|
+
? markdown
|
|
22
|
+
: `${markdown}${escapeSlackMarkdown(separator)}_${escapeSlackMarkdown(attribution)}_`;
|
|
21
23
|
}
|