@opengeni/worker-bundle 0.28.3-canary.0 → 0.28.4-canary.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 (27) hide show
  1. package/dist/activities/agent-turn/mcp-operation-read-tool.d.ts +16 -0
  2. package/dist/activities/mcp-operation-authority.d.ts +16 -0
  3. package/dist/activities/mcp-operation-observer.d.ts +14 -0
  4. package/dist/activities/mcp-operation-reader.d.ts +45 -0
  5. package/dist/activities/mcp-operation-store.d.ts +6 -0
  6. package/dist/{activities-control-JUBMDBDZ.js → activities-control-J5QNRWVH.js} +2 -1
  7. package/dist/{activities-control-JUBMDBDZ.js.map → activities-control-J5QNRWVH.js.map} +1 -1
  8. package/dist/{activities-turn-I2ZKGZE6.js → activities-turn-ZJBY3W5D.js} +15685 -792
  9. package/dist/activities-turn-ZJBY3W5D.js.map +1 -0
  10. package/dist/artifact-materializer-entry.js +2 -0
  11. package/dist/artifact-materializer-entry.js.map +1 -1
  12. package/dist/artifact-outbox-entry.js +2 -0
  13. package/dist/artifact-outbox-entry.js.map +1 -1
  14. package/dist/chunk-PZ5AY32C.js +10 -0
  15. package/dist/chunk-PZ5AY32C.js.map +1 -0
  16. package/dist/host-export.js +1 -0
  17. package/dist/index.js +2 -1
  18. package/dist/index.js.map +1 -1
  19. package/package.json +18 -17
  20. package/src/activities/agent-turn/mcp-operation-read-tool.ts +61 -0
  21. package/src/activities/agent-turn/tool-environment.ts +65 -0
  22. package/src/activities/mcp-credentials.ts +94 -40
  23. package/src/activities/mcp-operation-authority.ts +76 -0
  24. package/src/activities/mcp-operation-observer.ts +86 -0
  25. package/src/activities/mcp-operation-reader.ts +108 -0
  26. package/src/activities/mcp-operation-store.ts +98 -0
  27. package/dist/activities-turn-I2ZKGZE6.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/worker-bundle",
3
- "version": "0.28.3-canary.0",
3
+ "version": "0.28.4-canary.0",
4
4
  "description": "OpenGeni worker entry and reusable embedded lifecycle, shipped with a release-coherent pre-bundled Temporal workflow artifact.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -54,22 +54,23 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@llamaindex/liteparse": "2.14.2",
57
- "@opengeni/agent-proto": "^0.5.1-canary.25",
58
- "@opengeni/capabilities": "^0.3.3-canary.7",
59
- "@opengeni/codemode": "^0.5.5-canary.0",
60
- "@opengeni/codex": "^0.2.22-canary.7",
61
- "@opengeni/config": "^1.1.1-canary.0",
62
- "@opengeni/contracts": "^3.0.1-canary.0",
63
- "@opengeni/core": "^2.9.3-canary.0",
64
- "@opengeni/db": "^4.3.2-canary.0",
65
- "@opengeni/documents": "^0.8.26-canary.0",
66
- "@opengeni/events": "^0.4.24-canary.0",
67
- "@opengeni/github": "^0.7.9-canary.0",
68
- "@opengeni/network": "^0.3.1-canary.7",
69
- "@opengeni/observability": "^0.8.25-canary.0",
70
- "@opengeni/runtime": "^2.5.2-canary.0",
71
- "@opengeni/storage": "^0.2.126-canary.0",
72
- "@opengeni/xai-subscription": "^0.1.4-canary.7",
57
+ "@opengeni/agent-proto": "^0.5.1-canary.26",
58
+ "@opengeni/capabilities": "^0.3.3-canary.8",
59
+ "@opengeni/codemode": "^0.5.6-canary.0",
60
+ "@opengeni/codex": "^0.2.22-canary.8",
61
+ "@opengeni/config": "^1.1.2-canary.0",
62
+ "@opengeni/contracts": "^3.0.2-canary.0",
63
+ "@opengeni/core": "^2.9.4-canary.0",
64
+ "@opengeni/db": "^4.3.3-canary.0",
65
+ "@opengeni/documents": "^0.8.27-canary.0",
66
+ "@opengeni/events": "^0.4.25-canary.0",
67
+ "@opengeni/github": "^0.7.10-canary.0",
68
+ "@opengeni/network": "^0.3.1-canary.8",
69
+ "@opengeni/observability": "^0.8.26-canary.0",
70
+ "@opengeni/runtime": "^2.5.3-canary.0",
71
+ "@opengeni/storage": "^0.2.127-canary.0",
72
+ "@opengeni/tool-gateway": "^0.1.7-canary.0",
73
+ "@opengeni/xai-subscription": "^0.1.4-canary.8",
73
74
  "@temporalio/activity": "^1.17.0",
74
75
  "@temporalio/client": "^1.17.0",
75
76
  "@temporalio/worker": "^1.17.0",
@@ -0,0 +1,61 @@
1
+ import type { AttemptToolDefinition } from "@opengeni/codemode";
2
+ import { AttemptToolResult } from "@opengeni/contracts";
3
+ import { z } from "zod";
4
+
5
+ const selectorSchema = z.union([
6
+ z.object({ operationId: z.string().uuid() }).strict(),
7
+ z.object({ sourceTurnId: z.string().uuid(), sourceCallId: z.string().min(1) }).strict(),
8
+ ]);
9
+
10
+ export type McpOperationReadSelector = z.infer<typeof selectorSchema>;
11
+
12
+ /** Attempt-local adapter. The supplied read closure owns canonical session
13
+ * access, current provider authority, immutable binding checks and settlement.
14
+ * No caller-controlled provider parameters cross this tool boundary. */
15
+ export function createOperationReadAttemptToolDefinition(input: {
16
+ read: (selector: McpOperationReadSelector) => Promise<Record<string, unknown>>;
17
+ }): AttemptToolDefinition {
18
+ return {
19
+ identity: { serverId: "opengeni", toolName: "operation_read" },
20
+ modelName: "operation_read",
21
+ codemodePath: ["opengeni", "operation_read"],
22
+ title: "Read an existing MCP operation outcome",
23
+ description:
24
+ "Read a retained MCP operation and, when supported and currently authorized, observe its provider receipt. " +
25
+ "Use the operationId from the original call, or its exact sourceTurnId and sourceCallId if that response was lost. " +
26
+ "This never repeats the original mutation. Unknown means the outcome is not proven, not that the operation failed. " +
27
+ "Provider support and renewed authorization may be required after reconnecting.",
28
+ inputSchema: {
29
+ type: "object",
30
+ properties: {
31
+ operationId: { type: "string", format: "uuid" },
32
+ sourceTurnId: { type: "string", format: "uuid" },
33
+ sourceCallId: { type: "string", minLength: 1 },
34
+ },
35
+ additionalProperties: false,
36
+ oneOf: [
37
+ {
38
+ required: ["operationId"],
39
+ not: { anyOf: [{ required: ["sourceTurnId"] }, { required: ["sourceCallId"] }] },
40
+ },
41
+ { required: ["sourceTurnId", "sourceCallId"], not: { required: ["operationId"] } },
42
+ ],
43
+ },
44
+ annotations: {
45
+ readOnlyHint: true,
46
+ destructiveHint: false,
47
+ idempotentHint: true,
48
+ openWorldHint: true,
49
+ },
50
+ source: "opengeni",
51
+ approval: "none",
52
+ execute: async (args) => {
53
+ const selector = selectorSchema.parse(args);
54
+ const receipt = await input.read(selector);
55
+ return AttemptToolResult.parse({
56
+ content: [{ type: "text", text: JSON.stringify(receipt) }],
57
+ structuredContent: receipt,
58
+ });
59
+ },
60
+ };
61
+ }
@@ -37,6 +37,11 @@ import {
37
37
  resolveGoogleDrivePublicationTarget,
38
38
  } from "../google-drive-publication";
39
39
  import { connectionTokenResolverForTurn } from "../mcp-credentials";
40
+ import { createMcpOperationPersistence } from "@opengeni/db/mcp-operations";
41
+ import { createMcpOperationReadStore } from "../mcp-operation-store";
42
+ import { createMcpOperationObserverResolver } from "../mcp-operation-observer";
43
+ import { readMcpOperation } from "../mcp-operation-reader";
44
+ import { createOperationReadAttemptToolDefinition } from "./mcp-operation-read-tool";
40
45
  import { buildGitHubRestMcpForTurn } from "../../github-rest-mcp";
41
46
  import { materializeConnectorAttachmentsInChannel } from "../connector-attachments";
42
47
  import { allowedFirstPartyMcpToolsForSession, type Settings } from "@opengeni/config";
@@ -668,7 +673,66 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
668
673
  });
669
674
  },
670
675
  });
676
+ const operationRecoveryEnabled = githubRestMcp.settings.mcpServers.some(
677
+ (server) =>
678
+ server.operationRecovery &&
679
+ Object.keys(server.operationRecovery).length > 0 &&
680
+ githubRestMcp.tools.some((tool) => tool.kind === "mcp" && tool.id === server.id),
681
+ );
682
+ const operationAttempt = {
683
+ accountId: input.accountId,
684
+ workspaceId: input.workspaceId,
685
+ sessionId: input.sessionId,
686
+ turnId: turn.id,
687
+ attemptId: input.attemptId,
688
+ executionGeneration: attempt.executionGeneration,
689
+ };
690
+ const operationPersistence = operationRecoveryEnabled
691
+ ? createMcpOperationPersistence(db, operationAttempt)
692
+ : undefined;
693
+ const operationReadStore = operationRecoveryEnabled
694
+ ? createMcpOperationReadStore(db, operationAttempt)
695
+ : undefined;
696
+ const operationObserver = createMcpOperationObserverResolver({
697
+ settings: githubRestMcp.settings,
698
+ workspaceId: input.workspaceId,
699
+ ...(credentialSubjectId ? { credentialSubjectId } : {}),
700
+ resolveCredential,
701
+ assertAttempt: async () => {
702
+ throwIfWorkerShuttingDown();
703
+ throwIfTurnCancelled();
704
+ const current = await getSessionTurnForAttempt(
705
+ db,
706
+ input.workspaceId,
707
+ input.sessionId,
708
+ input.attemptId,
709
+ );
710
+ if (
711
+ !current ||
712
+ current.id !== turn.id ||
713
+ current.executionGeneration !== attempt.executionGeneration
714
+ ) {
715
+ throw new Error("MCP operation reader no longer owns the executing attempt");
716
+ }
717
+ },
718
+ getEnvironment: async () => {
719
+ const prepared = eventing.preparedTools;
720
+ if (!prepared) return null;
721
+ return ((await prepared.ready) ?? prepared).attemptToolEnvironment;
722
+ },
723
+ });
671
724
  const attemptToolDefinitions = [
725
+ ...(operationReadStore
726
+ ? [
727
+ createOperationReadAttemptToolDefinition({
728
+ read: async (selector) =>
729
+ await readMcpOperation(selector, {
730
+ ...operationReadStore,
731
+ resolveObserver: operationObserver,
732
+ }),
733
+ }),
734
+ ]
735
+ : []),
672
736
  ...skillTools,
673
737
  createListModelsAttemptToolDefinition({
674
738
  currentModelId: turnExecutionPolicy.productModelId,
@@ -876,6 +940,7 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
876
940
  ...(credentialSubjectId ? { credentialSubjectId } : {}),
877
941
  ...(codexAppsAuth ? { codexAppsAuth } : {}),
878
942
  resolveCredential,
943
+ ...(operationPersistence ? { mcpOperationPersistence: operationPersistence } : {}),
879
944
  ...(linkedAuthority
880
945
  ? {
881
946
  authorizeAttemptExecution: async () => {
@@ -1,5 +1,6 @@
1
1
  import type { Settings } from "@opengeni/config";
2
2
  import type { ConnectionCredentialsPort } from "@opengeni/contracts";
3
+ import type { HostMcpAcceptedAuthority } from "@opengeni/contracts/host-mcp-bindings";
3
4
  import {
4
5
  buildConnectionTokenResolver,
5
6
  buildHostConnectionTokenResolver,
@@ -13,6 +14,7 @@ import {
13
14
  type SessionTurnForExecution,
14
15
  } from "@opengeni/db";
15
16
  import { recordTenancyCompatibilityLaneUse, type Observability } from "@opengeni/observability";
17
+ import { mcpOperationAuthorityDigest } from "./mcp-operation-authority";
16
18
 
17
19
  const OPENGENI_CONNECTION_ID_PATTERN =
18
20
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
@@ -39,46 +41,78 @@ export function connectionTokenResolverForTurn(input: {
39
41
  const readHostTurn = input.getHostTurnForAttempt ?? getSessionTurnForAttempt;
40
42
  const hostDb = input.db;
41
43
  const nativeResolver = buildConnectionTokenResolver(input.db, input.settings);
44
+ const recoveryEnabled = (serverId: string) =>
45
+ input.settings.mcpServers.some(
46
+ (server) =>
47
+ server.id === serverId &&
48
+ "operationRecovery" in server &&
49
+ server.operationRecovery !== undefined &&
50
+ Object.keys(server.operationRecovery ?? {}).length > 0,
51
+ );
42
52
  const configuredResolver = hostResolver
43
- ? buildHostConnectionTokenResolver(hostResolver, {
44
- accountId: input.accountId,
45
- workspaceId: input.workspaceId,
46
- sessionId: input.sessionId,
47
- rootSessionId: input.rootSessionId,
48
- turnId: input.turn.id,
49
- attemptId: input.attemptId,
50
- executionGeneration: input.turn.executionGeneration,
51
- initiator: input.turn.initiator,
52
- initiatorContext: input.turn.initiatorContext,
53
- surface: "model",
54
- // Only immutable captured direct-turn authority is currently supported.
55
- // Direct, scheduled and exact causal/child snapshots are validated;
56
- // no authority follows merely from a binding or creator identity.
57
- authorizeDurableBinding: (request) => authorizeDirectHostMcpUse(hostDb, request),
58
- authorizeExecution: async (request) => {
59
- // Native UUID references already pass the accepted-use boundary below.
60
- // Legacy opaque host IDs retain their compatibility path, but not a
61
- // right to execute after their accepted attempt has stopped.
62
- if (
63
- request.connectionRef.authoritySource !== "host" &&
64
- (!request.connectionRef.connectionId ||
65
- OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId))
66
- )
67
- return true;
68
- if (!request.attemptId) return false;
69
- const current = await readHostTurn(
70
- hostDb,
71
- request.workspaceId,
72
- request.sessionId,
73
- request.attemptId,
74
- );
75
- return (
76
- current !== null &&
77
- current.id === request.turnId &&
78
- current.executionGeneration === request.executionGeneration
79
- );
80
- },
81
- })
53
+ ? async (
54
+ credentialRequest: ResolveConnectionCredentialInput,
55
+ ): Promise<ResolveConnectionCredentialResult> => {
56
+ let authorizedSnapshot: HostMcpAcceptedAuthority | undefined;
57
+ const wantsDigest = recoveryEnabled(credentialRequest.serverId);
58
+ const resolver = buildHostConnectionTokenResolver(hostResolver, {
59
+ accountId: input.accountId,
60
+ workspaceId: input.workspaceId,
61
+ sessionId: input.sessionId,
62
+ rootSessionId: input.rootSessionId,
63
+ turnId: input.turn.id,
64
+ attemptId: input.attemptId,
65
+ executionGeneration: input.turn.executionGeneration,
66
+ initiator: input.turn.initiator,
67
+ initiatorContext: input.turn.initiatorContext,
68
+ surface: "model",
69
+ // Only immutable captured direct-turn authority is currently supported.
70
+ // Direct, scheduled and exact causal/child snapshots are validated;
71
+ // no authority follows merely from a binding or creator identity.
72
+ authorizeDurableBinding: (request) =>
73
+ authorizeDirectHostMcpUse(
74
+ hostDb,
75
+ request,
76
+ wantsDigest
77
+ ? (snapshot) => {
78
+ authorizedSnapshot = snapshot;
79
+ }
80
+ : undefined,
81
+ ),
82
+ authorizeExecution: async (request) => {
83
+ // Native UUID references already pass the accepted-use boundary below.
84
+ // Legacy opaque host IDs retain their compatibility path, but not a
85
+ // right to execute after their accepted attempt has stopped.
86
+ if (
87
+ request.connectionRef.authoritySource !== "host" &&
88
+ (!request.connectionRef.connectionId ||
89
+ OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId))
90
+ )
91
+ return true;
92
+ if (!request.attemptId) return false;
93
+ const current = await readHostTurn(
94
+ hostDb,
95
+ request.workspaceId,
96
+ request.sessionId,
97
+ request.attemptId,
98
+ );
99
+ return (
100
+ current !== null &&
101
+ current.id === request.turnId &&
102
+ current.executionGeneration === request.executionGeneration
103
+ );
104
+ },
105
+ });
106
+ const result = await resolver(credentialRequest);
107
+ return result.status === "ok" && authorizedSnapshot
108
+ ? {
109
+ ...result,
110
+ operationAuthorityDigest: mcpOperationAuthorityDigest(credentialRequest, {
111
+ host: authorizedSnapshot,
112
+ }),
113
+ }
114
+ : result;
115
+ }
82
116
  : nativeResolver;
83
117
  const baseResolver = (request: ResolveConnectionCredentialInput) =>
84
118
  input.connectionCredentials?.mcpAuthoritySource === "host" &&
@@ -229,10 +263,30 @@ export function connectionTokenResolverForTurn(input: {
229
263
  });
230
264
  const withProviderRequestAuthorization = (
231
265
  result: ResolveConnectionCredentialResult,
266
+ attribution = result.status === "ok" ? result.connectionUseAttribution : undefined,
232
267
  ): ResolveConnectionCredentialResult => {
233
268
  if (result.status !== "ok") return result;
234
269
  return {
235
270
  ...result,
271
+ ...(attribution && recoveryEnabled(request.serverId)
272
+ ? {
273
+ operationAuthorityDigest: mcpOperationAuthorityDigest(request, {
274
+ native: attribution,
275
+ // Match the canonical DB recovery principal: a causal human
276
+ // survives goal/service continuations. These fields come from
277
+ // the accepted turn, never request.subjectId or caller JSON.
278
+ principal: input.turn.initiatingHumanSubjectId
279
+ ? { kind: "subject", subjectId: input.turn.initiatingHumanSubjectId }
280
+ : {
281
+ kind: input.turn.initiator.kind,
282
+ ...(input.turn.initiator.kind === "subject" ||
283
+ input.turn.initiator.kind === "service"
284
+ ? { subjectId: input.turn.initiator.subjectId }
285
+ : {}),
286
+ },
287
+ }),
288
+ }
289
+ : {}),
236
290
  authorizeProviderRequest: async () => {
237
291
  const authorization = await authorize({
238
292
  ...credentialUseContext,
@@ -286,7 +340,7 @@ export function connectionTokenResolverForTurn(input: {
286
340
  ? { subjectId: authorization.attribution.ownerSubjectId }
287
341
  : {}),
288
342
  });
289
- return withProviderRequestAuthorization(result);
343
+ return withProviderRequestAuthorization(result, authorization.attribution);
290
344
  };
291
345
  }
292
346
 
@@ -0,0 +1,76 @@
1
+ import { createHash } from "node:crypto";
2
+ import { stableJson } from "@opengeni/contracts";
3
+ import type { ConnectionUseAttribution } from "@opengeni/contracts/connection-authority";
4
+ import type { HostMcpAcceptedAuthority } from "@opengeni/contracts/host-mcp-bindings";
5
+ import type { ResolveConnectionCredentialInput } from "@opengeni/db";
6
+
7
+ /** Metadata only. Callers must obtain authority from a current live fence.
8
+ * This equality key is never authorization and never replaces physical-use checks. */
9
+ export function mcpOperationAuthorityDigest(
10
+ request: ResolveConnectionCredentialInput,
11
+ authority:
12
+ | {
13
+ native: ConnectionUseAttribution;
14
+ host?: never;
15
+ principal?: { kind: string; subjectId?: string };
16
+ }
17
+ | { host: HostMcpAcceptedAuthority; native?: never },
18
+ ): string {
19
+ const n = authority.native;
20
+ const h = authority.host;
21
+ const ref = request.connectionRef;
22
+ const metadata = {
23
+ version: 1,
24
+ serverId: request.serverId,
25
+ destinationUrl: request.destinationUrl,
26
+ credentialTarget: request.credentialTarget ?? "mcp",
27
+ connectionRef: {
28
+ authoritySource: ref.authoritySource,
29
+ connectionId: ref.connectionId,
30
+ provider: ref.provider,
31
+ providerDomain: ref.providerDomain,
32
+ kind: ref.kind,
33
+ subjectScope: ref.subjectScope,
34
+ hostBinding: ref.hostBinding,
35
+ scopes: ref.scopes ? [...ref.scopes].sort() : undefined,
36
+ resource: ref.resource,
37
+ selectedResources: ref.selectedResources
38
+ ? [...ref.selectedResources].sort((a, b) =>
39
+ stableJson(a) < stableJson(b) ? -1 : stableJson(a) > stableJson(b) ? 1 : 0,
40
+ )
41
+ : undefined,
42
+ },
43
+ native: n
44
+ ? {
45
+ organizationId: n.organizationId,
46
+ workspaceId: n.workspaceId,
47
+ sessionId: n.sessionId,
48
+ connectionId: n.connectionId,
49
+ connectionGeneration: n.connectionGeneration,
50
+ scope: n.scope,
51
+ ownerSubjectId: n.ownerSubjectId,
52
+ authorityId: n.authorityId,
53
+ grantId: n.grantId,
54
+ principal: "principal" in authority ? authority.principal : undefined,
55
+ }
56
+ : undefined,
57
+ host: h
58
+ ? {
59
+ accountId: h.accountId,
60
+ workspaceId: h.workspaceId,
61
+ targetSessionId: h.targetSessionId,
62
+ targetSessionVisibility: h.targetSessionVisibility,
63
+ targetSessionAuthorityEpoch: h.targetSessionAuthorityEpoch,
64
+ ownerSubjectId: h.ownerSubjectId,
65
+ ownerOrganizationMembershipId: h.ownerOrganizationMembershipId,
66
+ ownerMembershipAuthorizationRevision: h.ownerMembershipAuthorizationRevision,
67
+ bindingId: h.bindingId,
68
+ bindingGeneration: h.bindingGeneration,
69
+ definition: h.definition,
70
+ delegationId: h.delegationId,
71
+ delegationGeneration: h.delegationGeneration,
72
+ }
73
+ : undefined,
74
+ };
75
+ return createHash("sha256").update(stableJson(metadata)).digest("hex");
76
+ }
@@ -0,0 +1,86 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import type { AttemptToolEnvironment } from "@opengeni/codemode";
3
+ import { digestCanonicalJson } from "@opengeni/tool-gateway";
4
+ import {
5
+ runMcpOperationObservationWithAuthority,
6
+ type ResolveConnectionCredentialInput,
7
+ type ResolveConnectionCredentialResult,
8
+ } from "@opengeni/runtime";
9
+ import type { McpOperationReaderDependencies } from "./mcp-operation-reader";
10
+
11
+ /** Current-attempt adapter: no credential renewal authority survives this
12
+ * closure. The stored digest constrains fresh authority, never establishes it. */
13
+ export function createMcpOperationObserverResolver(input: {
14
+ settings: Pick<Settings, "mcpServers">;
15
+ workspaceId: string;
16
+ credentialSubjectId?: string;
17
+ assertAttempt: () => Promise<void>;
18
+ resolveCredential: (
19
+ request: ResolveConnectionCredentialInput,
20
+ ) => Promise<ResolveConnectionCredentialResult>;
21
+ getEnvironment: () => Promise<AttemptToolEnvironment | null>;
22
+ }): McpOperationReaderDependencies["resolveObserver"] {
23
+ return async (operation) => {
24
+ await input.assertAttempt();
25
+ const configured = input.settings.mcpServers.find(
26
+ (candidate) => candidate.id === operation.serverId,
27
+ );
28
+ const recovery = configured?.operationRecovery?.[operation.originalTool];
29
+ if (!configured?.connectionRef || !recovery) return { status: "unsupported" };
30
+ const destinationUrl = new URL(configured.url).toString();
31
+ if (
32
+ recovery.observerTool !== operation.observerTool ||
33
+ digestCanonicalJson(destinationUrl) !== operation.destinationDigest
34
+ ) {
35
+ return { status: "binding_changed" };
36
+ }
37
+ const connectionRef = structuredClone(configured.connectionRef);
38
+ const environment = await input.getEnvironment();
39
+ const observerEntry = environment?.catalog.entries.find(
40
+ (entry) =>
41
+ entry.identity.serverId === operation.serverId &&
42
+ entry.identity.toolName === operation.observerTool,
43
+ );
44
+ if (!environment || !observerEntry) return { status: "unsupported" };
45
+
46
+ const authorize = async () => {
47
+ await input.assertAttempt();
48
+ const resolved = await input.resolveCredential({
49
+ workspaceId: input.workspaceId,
50
+ serverId: operation.serverId,
51
+ toolName: operation.observerTool,
52
+ connectionRef,
53
+ destinationUrl,
54
+ forceRefresh: false,
55
+ ...(input.credentialSubjectId ? { subjectId: input.credentialSubjectId } : {}),
56
+ });
57
+ // This is credential-resolution authorization. The actual broker keeps
58
+ // ownership of the physical provider-request authorization/audit fact.
59
+ return (
60
+ resolved.status === "ok" && resolved.operationAuthorityDigest === operation.authorityDigest
61
+ );
62
+ };
63
+ if (!(await authorize())) return { status: "auth_needed" };
64
+ return {
65
+ status: "ready",
66
+ authorize,
67
+ callObserver: async (tool, args) => {
68
+ if (tool !== operation.observerTool) throw new Error("MCP observer binding changed");
69
+ return await runMcpOperationObservationWithAuthority(
70
+ {
71
+ serverId: operation.serverId,
72
+ observerTool: operation.observerTool,
73
+ destinationDigest: operation.destinationDigest,
74
+ authorityDigest: operation.authorityDigest,
75
+ },
76
+ async () =>
77
+ await environment.callModel({
78
+ modelName: observerEntry.modelName,
79
+ arguments: args,
80
+ subjectId: "worker:first-party-mcp",
81
+ }),
82
+ );
83
+ },
84
+ };
85
+ };
86
+ }
@@ -0,0 +1,108 @@
1
+ import type { AttemptToolResult } from "@opengeni/contracts";
2
+ import { observeMcpOperation, type McpObservationReceipt } from "@opengeni/runtime";
3
+ import type { McpOperationReadSelector } from "./agent-turn/mcp-operation-read-tool";
4
+
5
+ type TerminalReceipt = Extract<McpObservationReceipt, { status: "completed" }>;
6
+
7
+ /** Internal, credential-free projection loaded through canonical current
8
+ * attempt/session authorization. Never return this object directly to tools. */
9
+ export type McpOperationReadRecord = {
10
+ operationId: string;
11
+ sourceTurnId: string;
12
+ sourceCallId: string | null;
13
+ serverId: string;
14
+ originalTool: string;
15
+ observerTool: string;
16
+ argumentDigest: string;
17
+ destinationDigest: string;
18
+ authorityDigest: string;
19
+ originalOutcome: "captured" | "completed" | "outcome_unknown";
20
+ originalResult: AttemptToolResult | null;
21
+ receipt: TerminalReceipt | null;
22
+ };
23
+
24
+ type ObserverResolution =
25
+ | { status: "unsupported" | "auth_needed" | "binding_changed" }
26
+ | {
27
+ status: "ready";
28
+ authorize: (phase: "before_request" | "before_delivery") => Promise<boolean>;
29
+ callObserver: (tool: string, args: Record<string, unknown>) => Promise<unknown>;
30
+ };
31
+
32
+ export type McpOperationReaderDependencies = {
33
+ /** Includes live attempt and original-principal/session disclosure checks. */
34
+ load: (selector: McpOperationReadSelector) => Promise<McpOperationReadRecord | null>;
35
+ claim: (operationId: string) => Promise<string | null>;
36
+ release: (operationId: string, claimId: string) => Promise<void>;
37
+ /** Claim-fenced transaction storing one immutable receipt. Must recheck
38
+ * canonical current authority and never rewrite the original outcome.
39
+ * Delivery uses the ordinary operation_read tool-result lifecycle. */
40
+ settle: (
41
+ operationId: string,
42
+ claimId: string,
43
+ receipt: TerminalReceipt,
44
+ ) => Promise<McpOperationReadRecord>;
45
+ /** Binds the current trusted config/connection to the persisted original
46
+ * digests. Model arguments may not supply or replace any of that authority. */
47
+ resolveObserver: (operation: McpOperationReadRecord) => Promise<ObserverResolution>;
48
+ };
49
+
50
+ /** One explicit read; no timer, inference wake, or mutation replay. */
51
+ export async function readMcpOperation(
52
+ selector: McpOperationReadSelector,
53
+ dependencies: McpOperationReaderDependencies,
54
+ ): Promise<Record<string, unknown>> {
55
+ const operation = await dependencies.load(selector);
56
+ if (!operation) throw new Error("MCP operation is unavailable");
57
+ if (operation.receipt || operation.originalOutcome === "completed") return project(operation);
58
+
59
+ const observer = await dependencies.resolveObserver(operation);
60
+ if (observer.status !== "ready") return project(operation, { status: observer.status });
61
+ const claimId = await dependencies.claim(operation.operationId);
62
+ if (!claimId) {
63
+ // A competing reader may have committed after our initial load. Re-read
64
+ // under current authority instead of returning an old cached projection.
65
+ const fresh = await dependencies.load({ operationId: operation.operationId });
66
+ if (!fresh) throw new Error("MCP operation is unavailable");
67
+ return project(
68
+ fresh,
69
+ fresh.receipt || fresh.originalOutcome === "completed"
70
+ ? undefined
71
+ : { status: "observation_in_progress" },
72
+ );
73
+ }
74
+ let settled = false;
75
+ try {
76
+ const receipt = await observeMcpOperation({
77
+ binding: {
78
+ operationId: operation.operationId,
79
+ serverId: operation.serverId,
80
+ originalTool: operation.originalTool,
81
+ observerTool: operation.observerTool,
82
+ argumentDigest: operation.argumentDigest,
83
+ },
84
+ authorize: observer.authorize,
85
+ callObserver: observer.callObserver,
86
+ });
87
+ if (receipt.status !== "completed") return project(operation, receipt);
88
+ const recorded = await dependencies.settle(operation.operationId, claimId, receipt);
89
+ settled = true;
90
+ return project(recorded);
91
+ } finally {
92
+ if (!settled) await dependencies.release(operation.operationId, claimId);
93
+ }
94
+ }
95
+
96
+ function project(
97
+ operation: McpOperationReadRecord,
98
+ observation?: Record<string, unknown>,
99
+ ): Record<string, unknown> {
100
+ return {
101
+ operationId: operation.operationId,
102
+ original: { turnId: operation.sourceTurnId, sourceCallId: operation.sourceCallId },
103
+ invocationOutcome:
104
+ operation.originalOutcome === "captured" ? "outcome_unknown" : operation.originalOutcome,
105
+ ...(operation.originalOutcome === "completed" ? { result: operation.originalResult } : {}),
106
+ observation: observation ?? operation.receipt ?? { status: "unknown" },
107
+ };
108
+ }