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

McpClientInput.ts

170 lines7.8 KB

1import type { ProviderApprovalPushHooks } from "@t3tools/contracts";
2import type * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7import * as Schema from "effect/Schema";
8import { McpSchema } from "effect/ai";
9​
10import * as McpInvocationContext from "./McpInvocationContext.ts";
11​
12/**
13 * Where one tool call leaves its request for the client's input. A sessionless client is asked
14 * by answering the call with that request; it calls the tool again with the person's answer.
15 * `McpHttpServer` provides this around every call and sends what the handler left here.
16 */
17export class McpClientInput extends Context.Service<
18 McpClientInput,
19 {
20 readonly request: Ref.Ref<McpSchema.InputRequired | undefined>;
21 /** Where a thread's adapter finds what T3 Code asks through the thread's own client. */
22 readonly sessions?: McpProviderSessions.McpProviderSessions["Service"] | undefined;
23 }
24>()("t3/mcp/McpClientInput") {}
25​
26/**
27 * "asked": the request went out with this call's answer, so the handler ends now and runs again
28 * when the client calls back. "unavailable": this client cannot ask a person anything.
29 * "unconfirmed": the client replied that the person accepted, and T3 Code, which showed the
30 * request to the person itself, has no approval from them for it.
31 */
32export type Approval = "accepted" | "declined" | "unconfirmed" | "asked" | "unavailable";
33​
34const consentForm = { type: "object", properties: {} } as const;
35const decodeElicitRequest = Schema.decodeEffect(McpSchema.ElicitRequestFormParams);
36​
37// A request left with a thread's session goes out with that record's id after its state, so the
38// reply that comes with a later call ends that record and no other.
39const RECORDED_STATE = /^(.*) request=([0-9a-f-]{36})$/s;
40const recordedState = (state: string, id: string | undefined) =>
41 id === undefined ? state : `${state} request=${id}`;
42const sentState = (requestState: string) => {
43 const match = RECORDED_STATE.exec(requestState);
44 return match === null ? { state: requestState } : { state: match[1]!, id: match[2]! };
45};
46​
47/** The calling thread and where its requests are kept, when the call comes from a thread. */
48const threadRequests = Effect.gen(function* () {
49 const sessions = Option.getOrUndefined(yield* Effect.serviceOption(McpClientInput))?.sessions;
50 const thread = Option.getOrUndefined(
51 yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
52 )?.thread;
53 return sessions === undefined || thread === undefined ? undefined : { sessions, thread };
54});
55​
56/**
57 * Ends the request `id` and reads the client's "accept" for it. Where the thread's adapter shows
58 * T3 Code's own requests, only the person's answer in the app, for this request and `state`, is
59 * an approval, and a request that is gone has none. Any other client's reply is all there is.
60 */
61const accepted = Effect.fnUntraced(function* (id: string | undefined, state?: string) {
62 const requests = yield* threadRequests;
63 if (requests === undefined) return "accepted" as const;
64 const { sessions, thread } = requests;
65 const request =
66 id === undefined ? undefined : yield* sessions.takeApprovalRequest(thread.threadId, id);
67 if (!(yield* sessions.areApprovalRequestsShown(thread.providerInstanceId))) {
68 return "accepted" as const;
69 }
70 return request?.approved === true && (state === undefined || request.state === state)
71 ? ("accepted" as const)
72 : ("unconfirmed" as const);
73});
74​
75/**
76 * The reply this call brings to `key`, with the `state` of the request it answers: what a
77 * sessionless client sends when it calls again. A handler reads it before it does anything a
78 * decline rules out, and it is read once: the request it answers is no longer waiting, so the
79 * thread's session forgets it.
80 */
81export const answered = Effect.fn("McpClientInput.answered")(function* (key: string) {
82 const context = Option.getOrUndefined(yield* Effect.serviceOption(McpSchema.McpRequestContext));
83 const answer = context?.inputResponses?.[key];
84 if (answer === undefined || context?.requestState === undefined) return undefined;
85 const { state, id } = sentState(context.requestState);
86 if (answer.action === "accept") return { state, answer: yield* accepted(id, state) };
87 const requests = yield* threadRequests;
88 if (requests !== undefined && id !== undefined) {
89 yield* requests.sessions.forgetApprovalRequest(requests.thread.threadId, id);
90 }
91 return { state, answer: "declined" as const };
92});
93​
94/**
95 * Asks the person behind the calling MCP client to approve `message`, by MCP elicitation.
96 * `state` names what is being approved: an answer counts only for the state it was given for,
97 * so asking again with another state asks the person again.
98 */
99export const askApproval = Effect.fn("McpClientInput.askApproval")(function* (input: {
100 readonly key: string;
101 readonly state: string;
102 readonly message: string;
103 readonly pushHooks?: ProviderApprovalPushHooks;
104}): Effect.fn.Return<Approval> {
105 const context = Option.getOrUndefined(yield* Effect.serviceOption(McpSchema.McpRequestContext));
106 const elicitation = context?.clientCapabilities.elicitation;
107 // The request is a form. A client that names no mode takes forms; one naming only URLs does not.
108 if (
109 context === undefined ||
110 elicitation === undefined ||
111 (elicitation.form === undefined && elicitation.url !== undefined)
112 ) {
113 return "unavailable";
114 }
115 const params = { mode: "form", message: input.message, requestedSchema: consentForm } as const;
116 const pending = Option.getOrUndefined(yield* Effect.serviceOption(McpClientInput));
117 const requests = yield* threadRequests;
118 // A thread's client hands its adapter the message and a server name to show. The request is
119 // left with the thread's MCP session too, so the adapter knows T3 Code asked it and what it
120 // names, and has where to leave the person's answer.
121 const record =
122 requests === undefined
123 ? Effect.undefined
124 : requests.sessions.recordApprovalRequest(requests.thread.threadId, {
125 message: input.message,
126 pushHooks: input.pushHooks,
127 state: input.state,
128 });
129​
130 // A session: the server asks over it and waits here for the answer.
131 const session = Option.getOrUndefined(yield* Effect.serviceOption(McpSchema.McpServerClient));
132 if (session !== undefined) {
133 const request = yield* decodeElicitRequest(params).pipe(Effect.orDie);
134 const recorded = yield* record;
135 return yield* session.getClient.pipe(
136 Effect.flatMap((client) => client.elicit(request)),
137 Effect.scoped,
138 Effect.flatMap(({ action }) =>
139 action === "accept" ? accepted(recorded) : Effect.succeed("declined" as const),
140 ),
141 // A request that ends without an answer is not an approval.
142 Effect.catchCause(() => Effect.succeed("declined" as const)),
143 Effect.ensuring(
144 requests === undefined || recorded === undefined
145 ? Effect.void
146 : requests.sessions.forgetApprovalRequest(requests.thread.threadId, recorded),
147 ),
148 );
149 }
150​
151 if (pending === undefined) return "unavailable";
152 const answer = context.inputResponses?.[input.key];
153 const sent = context.requestState === undefined ? undefined : sentState(context.requestState);
154 if (answer !== undefined && sent?.state === input.state) {
155 if (answer.action === "accept") return yield* accepted(sent.id, sent.state);
156 if (requests !== undefined && sent.id !== undefined) {
157 yield* requests.sessions.forgetApprovalRequest(requests.thread.threadId, sent.id);
158 }
159 return "declined";
160 }
161 const recorded = yield* record;
162 yield* Ref.set(
163 pending.request,
164 new McpSchema.InputRequired({
165 inputRequests: { [input.key]: { method: "elicitation/create", params } },
166 requestState: recordedState(input.state, recorded),
167 }),
168 );
169 return "asked";
170});