Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpAppModelContext.ts

160 lines6.0 KB

1import type { ThreadId, TurnItemId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8import * as SqlClient from "effect/sql/SqlClient";
9​
10export const MCP_APP_MODEL_CONTEXT_MAX_BYTES = 16 * 1024;
11​
12export class McpAppModelContextError extends Schema.TaggedError<McpAppModelContextError>()(
13 "McpAppModelContextError",
14 { cause: Schema.optional(Schema.Defect()) },
15) {}
16​
17export interface McpAppModelContextEntry {
18 readonly itemId: string;
19 readonly server: string;
20 readonly tool: string;
21 readonly text: string;
22 /** ISO time the app last set the note. */
23 readonly updatedAt: string;
25​
26export class McpAppModelContext extends Context.Service<
27 McpAppModelContext,
28 {
29 /** Empty text removes the app's context. */
30 readonly set: (input: {
31 readonly threadId: ThreadId;
32 readonly itemId: TurnItemId;
33 readonly server: string;
34 readonly tool: string;
35 readonly text: string;
36 }) => Effect.Effect<void, McpAppModelContextError>;
37 readonly forThread: (
38 threadId: ThreadId,
39 ) => Effect.Effect<ReadonlyArray<McpAppModelContextEntry>, McpAppModelContextError>;
40 }
41>()("t3/mcpApps/McpAppModelContext") {}
42​
43/** The thread's notes as a provider turn or steer sends them; a failed read sends none. */
44export const forProvider = Effect.fn("McpAppModelContext.forProvider")(function* (
45 modelContext: McpAppModelContext["Service"],
46 threadId: ThreadId,
47) {
48 const entries = yield* modelContext
49 .forThread(threadId)
50 .pipe(
51 Effect.catch((cause) =>
52 Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
53 Effect.as([] as ReadonlyArray<McpAppModelContextEntry>),
54 ),
55 ),
56 );
57 return entries.map((entry) => ({
58 // The item id alone is unique and needs no escaping; server and
59 // tool names are free text that would break the tag Codex wraps
60 // the context in.
61 key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
62 text: entry.text,
63 updatedAt: entry.updatedAt,
64 }));
65});
66​
67export const layer = Layer.effect(
68 McpAppModelContext,
69 Effect.gen(function* () {
70 const sql = yield* SqlClient.SqlClient;
71 const fail = (cause: unknown) => new McpAppModelContextError({ cause });
72​
73 const set = Effect.fn("McpAppModelContext.set")(function* (input: {
74 readonly threadId: ThreadId;
75 readonly itemId: TurnItemId;
76 readonly server: string;
77 readonly tool: string;
78 readonly text: string;
79 }) {
80 if (input.text.trim() === "") {
81 yield* sql`
82 DELETE FROM mcp_app_model_context
83 WHERE thread_id = ${input.threadId} AND item_id = ${input.itemId}
84 `.pipe(Effect.mapError(fail));
85 return;
86 }
87 const updatedAt = DateTime.formatIso(yield* DateTime.now);
88 yield* sql`
89 INSERT INTO mcp_app_model_context (thread_id, item_id, server, tool, text, updated_at)
90 VALUES (${input.threadId}, ${input.itemId}, ${input.server}, ${input.tool}, ${input.text}, ${updatedAt})
91 ON CONFLICT(thread_id, item_id) DO UPDATE SET text = excluded.text, updated_at = excluded.updated_at
92 `.pipe(Effect.mapError(fail));
93 });
94​
95 const forThread = Effect.fn("McpAppModelContext.forThread")(function* (threadId: ThreadId) {
96 // Match by id across fork lineage; later source rollbacks leave the fork's copy intact,
97 // while a started non-scheduled /clear (freshContext) run on this thread clears older notes.
98 return yield* sql<McpAppModelContextEntry>`
99 WITH boundary AS (
100 SELECT COALESCE(MAX(b.ordinal), 0) AS min_ordinal
101 FROM orchestration_v2_projection_runs AS b
102 WHERE b.thread_id = ${threadId}
103 AND json_extract(b.payload_json, '$.freshContext') = 1
104 AND b.status <> 'queued'
105 AND NOT (
106 b.status = 'cancelled'
107 AND json_extract(b.payload_json, '$.startedAt') IS NULL
108 AND json_extract(b.payload_json, '$.restartContinuationOfRunId') IS NULL
109 )
110 -- Mirrors isScheduledFreshRun: the run's first prompt, else its userMessageId's row.
111 AND (
112 SELECT json_extract(ti.payload_json, '$.scheduledTaskId')
113 FROM orchestration_v2_projection_turn_items AS ti
114 WHERE ti.thread_id = b.thread_id
115 AND ti.type = 'user_message'
116 AND (
117 ti.run_id = b.run_id
118 OR json_extract(ti.payload_json, '$.messageId') = json_extract(b.payload_json, '$.userMessageId')
119 )
120 ORDER BY ti.run_id = b.run_id DESC, ti.ordinal
121 LIMIT 1
122 ) IS NULL
123 )
124 SELECT context.item_id AS "itemId", context.server, context.tool, context.text,
125 context.updated_at AS "updatedAt"
126 FROM mcp_app_model_context AS context
127 CROSS JOIN boundary
128 JOIN orchestration_v2_projection_turn_items AS item
129 ON item.turn_item_id = context.item_id
130 LEFT JOIN orchestration_v2_projection_runs AS run
131 ON run.run_id = item.run_id
132 WHERE context.thread_id = ${threadId}
133 AND (
134 run.status IS NULL
135 OR run.status <> 'rolled_back'
136 OR run.thread_id <> context.thread_id
137 )
138 AND (
139 boundary.min_ordinal = 0
140 OR (run.thread_id = context.thread_id AND run.ordinal >= boundary.min_ordinal)
141 )
142 ORDER BY context.updated_at, context.item_id
143 `.pipe(NodeSqliteClient.readOnly, Effect.mapError(fail));
144 });
145​
146 return McpAppModelContext.of({ set, forThread });
147 }),
148);
149​
150export const layerEmpty = Layer.succeed(
151 McpAppModelContext,
152 McpAppModelContext.of({
153 set: Effect.fn("McpAppModelContext.set")(function () {
154 return Effect.void;
155 }),
156 forThread: Effect.fn("McpAppModelContext.forThread")(function () {
157 return Effect.succeed([]);
158 }),
159 }),
160);