@segmentstream/ontology 0.95.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.
Files changed (44) hide show
  1. package/README.md +39 -4
  2. package/dist/analyze.d.ts +23 -3
  3. package/dist/analyze.js +431 -17
  4. package/dist/authoring.js +3 -0
  5. package/dist/bin/check.js +2 -0
  6. package/dist/diagnostics.d.ts +3 -3
  7. package/dist/diagnostics.js +2 -0
  8. package/dist/index.d.ts +5 -3
  9. package/dist/index.js +3 -2
  10. package/dist/manifest.d.ts +607 -20
  11. package/dist/manifest.js +96 -4
  12. package/dist/migrate/apply.js +5 -1
  13. package/dist/migrate/model.d.ts +332 -12
  14. package/dist/migrate/storage.js +2 -0
  15. package/dist/ontology.d.ts +5 -2
  16. package/dist/ontology.js +1 -0
  17. package/dist/runtime/member-tables.d.ts +7 -2
  18. package/dist/runtime/member-tables.js +18 -3
  19. package/dist/runtime/new-user-hook.d.ts +11 -1
  20. package/dist/runtime/new-user-hook.js +69 -29
  21. package/dist/runtime/pipeline.d.ts +2 -0
  22. package/dist/runtime/pipeline.js +11 -3
  23. package/dist/runtime/principals.d.ts +13 -0
  24. package/dist/runtime/principals.js +98 -28
  25. package/dist/runtime/resolve-agent-identity.js +43 -12
  26. package/dist/runtime/service-binding.js +10 -4
  27. package/dist/service/catalog.js +10 -1
  28. package/dist/service/chat/envelope.d.ts +16 -16
  29. package/dist/service/connections.js +1 -0
  30. package/dist/service/discovery-search.d.ts +1 -1
  31. package/dist/service/mcp/server.js +13 -1
  32. package/dist/service/mcp/tools.d.ts +5 -0
  33. package/dist/service/mcp/tools.js +30 -0
  34. package/dist/service/operations.d.ts +3 -1
  35. package/dist/service/operations.js +3 -0
  36. package/dist/service/schemas.d.ts +74 -0
  37. package/dist/service/toolsets.d.ts +49 -0
  38. package/dist/service/toolsets.js +284 -0
  39. package/dist/sign-in.d.ts +32 -1
  40. package/dist/sign-in.js +12 -1
  41. package/dist/toolset.d.ts +141 -0
  42. package/dist/toolset.js +154 -0
  43. package/dist/user-identity.d.ts +1 -1
  44. package/package.json +1 -1
@@ -29,6 +29,7 @@ import { RequestId, errorBodyForWire, expectedFailure, internalError, isStorageF
29
29
  import { publicOrigin } from "../oauth/protocol.js";
30
30
  import { mcpChallenge, mcpResource } from "../oauth/server.js";
31
31
  import { identityToken, makeOperations, toQuery } from "../operations.js";
32
+ import { resultText } from "../toolsets.js";
32
33
  import { OntologyBackend } from "../runtime-contract.js";
33
34
  import { WarehouseQueries } from "../warehouse-platform.js";
34
35
  import { runtimeCredential } from "../runtime-identity.js";
@@ -453,6 +454,17 @@ function runTool(server, tool, args, request, preview) {
453
454
  const { id, ...params } = yield* decodeArguments(HistoryArguments, args);
454
455
  return structured(yield* encoded(HistoryPage, yield* operations.history(target.planned, id, params)));
455
456
  }
457
+ case "toolset": {
458
+ // Every argument is the provider's: toolset tools take no action options.
459
+ const result = yield* operations.runToolsetTool(target.toolset, target.tool, {
460
+ input: args,
461
+ identityToken: identityToken(request),
462
+ });
463
+ return {
464
+ text: resultText(result),
465
+ structured: (result.structuredContent ?? { content: result.content }),
466
+ };
467
+ }
456
468
  case "action": {
457
469
  if (target.planned.name === "agent_chat" && target.action.name === "post_message") {
458
470
  yield* decodeArguments(caller.kind === "runtime" ? RuntimeChatPostWire : ChatPostWire, args);
@@ -512,7 +524,7 @@ function callTool(server, params, request, preview) {
512
524
  }
513
525
  if (tool === undefined) {
514
526
  const candidates = visibleTools(server.tools, principal, caller)
515
- .filter((candidate) => candidate.target.kind === "action")
527
+ .filter((candidate) => candidate.target.kind === "action" || candidate.target.kind === "toolset")
516
528
  .map((candidate) => candidate.name);
517
529
  const suggestions = typeof call.name === "string" ? suggestNames(call.name, candidates) : [];
518
530
  return {
@@ -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
@@ -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
  };
@@ -423,9 +423,15 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
423
423
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Unknown>>;
424
424
  readonly onNewUser: Schema.optionalKey<Schema.String>;
425
425
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
426
+ readonly signUp: Schema.optionalKey<Schema.Struct<{
427
+ readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
428
+ }>>;
429
+ readonly onSignUp: Schema.optionalKey<Schema.String>;
426
430
  }>, {
427
431
  readonly onNewUser: "on_new_user";
428
432
  readonly codeLink: "code_link";
433
+ readonly signUp: "sign_up";
434
+ readonly onSignUp: "on_sign_up";
429
435
  }>>;
430
436
  readonly emails: Schema.optionalKey<Schema.$Record<Schema.String, Schema.encodeKeys<Schema.Struct<{
431
437
  readonly subject: Schema.String;
@@ -506,6 +512,37 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
506
512
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
507
513
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
508
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
+ }>>>;
509
546
  }>, Schema.Struct<{
510
547
  readonly entities: Schema.toEncoded<Schema.$Array<Schema.encodeKeys<Schema.Struct<{
511
548
  readonly metrics: Schema.optionalKey<Schema.$Array<Schema.encodeKeys<Schema.Struct<{
@@ -658,9 +695,15 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
658
695
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Unknown>>;
659
696
  readonly onNewUser: Schema.optionalKey<Schema.String>;
660
697
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
698
+ readonly signUp: Schema.optionalKey<Schema.Struct<{
699
+ readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
700
+ }>>;
701
+ readonly onSignUp: Schema.optionalKey<Schema.String>;
661
702
  }>, {
662
703
  readonly onNewUser: "on_new_user";
663
704
  readonly codeLink: "code_link";
705
+ readonly signUp: "sign_up";
706
+ readonly onSignUp: "on_sign_up";
664
707
  }>>>;
665
708
  readonly emails: Schema.toEncoded<Schema.optionalKey<Schema.$Record<Schema.String, Schema.encodeKeys<Schema.Struct<{
666
709
  readonly subject: Schema.String;
@@ -741,6 +784,37 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
741
784
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
742
785
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
743
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
+ }>>>>;
744
818
  }>, never, never>;
745
819
  export declare const Graph: Schema.Struct<{
746
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/sign-in.d.ts CHANGED
@@ -7,9 +7,34 @@ export declare const SIGN_IN_POLICIES: readonly ["invited", "open"];
7
7
  export type SignInPolicy = (typeof SIGN_IN_POLICIES)[number];
8
8
  /** An internal app is closed by default: a person enters by invitation. */
9
9
  export declare const DEFAULT_SIGN_IN_POLICY: SignInPolicy;
10
- /** Channels this SDK can enforce at admission. */
10
+ /** Channels `signIn.channels` can open; `signUp` replaces it. */
11
11
  export declare const CHANNEL_PROVIDERS: readonly ["telegram"];
12
12
  export type ChannelProvider = (typeof CHANNEL_PROVIDERS)[number];
13
+ /**
14
+ * The channels a stranger may sign up through. `email` is sign-in by email code in the app; the
15
+ * others are a first private message to the agent, or opening the Telegram Mini App.
16
+ */
17
+ export declare const SIGN_UP_CHANNELS: readonly ["email", "telegram", "whatsapp"];
18
+ export type SignUpChannel = (typeof SIGN_UP_CHANNELS)[number];
19
+ /** The sign-up channels a person reaches through a chat, which need a matching `chat` adapter. */
20
+ export declare const SIGN_UP_CHAT_CHANNELS: ReadonlyArray<SignUpChannel>;
21
+ export declare function isSignUpChannel(value: unknown): value is SignUpChannel;
22
+ /**
23
+ * Where a stranger may become a user, and the roles they are given. A channel not listed admits
24
+ * only invited or paired people. A user created by sign-up holds exactly these roles, granted like
25
+ * any other and revocable one person at a time, and never the `member` baseline of invited people.
26
+ */
27
+ export interface SignUpOptions<R = unknown> {
28
+ readonly channels: ReadonlyArray<SignUpChannel>;
29
+ /** Declared roles, as role objects or names; an empty list gives nothing beyond explicit grants. */
30
+ readonly roles: ReadonlyArray<R>;
31
+ /** Roles for a listed channel that differs from `roles`. */
32
+ readonly byChannel?: Readonly<Partial<Record<SignUpChannel, ReadonlyArray<R>>>>;
33
+ }
34
+ /** Sign-up as the manifest carries it: the wire names of the roles each open channel grants. */
35
+ export interface ResolvedSignUp {
36
+ readonly channels: Readonly<Partial<Record<SignUpChannel, ReadonlyArray<string>>>>;
37
+ }
13
38
  /** How people become members of the app. Email and channel admission are independent. */
14
39
  export interface SignInOptions {
15
40
  readonly policy: SignInPolicy;
@@ -25,6 +50,12 @@ export interface SignInOptions {
25
50
  */
26
51
  readonly codeLink?: boolean;
27
52
  }
53
+ /** The sign-in options of a checked ontology, with the sign-up its definition declares. */
54
+ export interface ResolvedSignInOptions extends SignInOptions {
55
+ readonly signUp?: ResolvedSignUp;
56
+ /** Wire name of the idempotent, input-free action run as each user created by sign-up. */
57
+ readonly onSignUp?: string;
58
+ }
28
59
  /**
29
60
  * How a person signs in with an address. `code`: a six-digit code, for a member who has signed in
30
61
  * with Neon Auth before, so their Neon Auth account exists. `link`: an emailed sign-in link, for
package/dist/sign-in.js CHANGED
@@ -6,8 +6,19 @@
6
6
  export const SIGN_IN_POLICIES = ["invited", "open"];
7
7
  /** An internal app is closed by default: a person enters by invitation. */
8
8
  export const DEFAULT_SIGN_IN_POLICY = "invited";
9
- /** Channels this SDK can enforce at admission. */
9
+ // @legacy ontology.legacy-channel-admission
10
+ /** Channels `signIn.channels` can open; `signUp` replaces it. */
10
11
  export const CHANNEL_PROVIDERS = ["telegram"];
12
+ /**
13
+ * The channels a stranger may sign up through. `email` is sign-in by email code in the app; the
14
+ * others are a first private message to the agent, or opening the Telegram Mini App.
15
+ */
16
+ export const SIGN_UP_CHANNELS = ["email", "telegram", "whatsapp"];
17
+ /** The sign-up channels a person reaches through a chat, which need a matching `chat` adapter. */
18
+ export const SIGN_UP_CHAT_CHANNELS = ["telegram", "whatsapp"];
19
+ export function isSignUpChannel(value) {
20
+ return SIGN_UP_CHANNELS.includes(value);
21
+ }
11
22
  /**
12
23
  * How a person signs in with an address. `code`: a six-digit code, for a member who has signed in
13
24
  * with Neon Auth before, so their Neon Auth account exists. `link`: an emailed sign-in link, for