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

mcpInjection.ts

318 lines9.5 KB

1import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4​
5import type { McpProviderSessionConfig } from "@t3tools/provider-core/server/mcpSession";
6import {
7 PI_T3_MCP_EXTENSION_FILENAME,
8 PI_T3_MCP_EXTENSION_SOURCE,
9 T3_MCP_BEARER_ENV,
10 T3_MCP_URL_ENV,
11 T3_PI_RUNTIME_MODE_ENV,
12 T3_PI_MCP_EXTENSION_PATH_ENV,
13} from "./mcpExtensionSource.ts";
14​
15const RESERVED_PI_LAUNCH_ARGUMENTS = new Set([
16 "--continue",
17 "-c",
18 "--export",
19 "--fork",
20 "--help",
21 "-h",
22 "--list-models",
23 "--mode",
24 "--no-session",
25 "--print",
26 "-p",
27 "--resume",
28 "-r",
29 "--session",
30 "--session-id",
31 "--version",
32 "-v",
33]);
34​
35const PI_ARGUMENTS_WITH_VALUES = new Set([
36 "--api-key",
37 "--append-system-prompt",
38 "--exclude-tools",
39 "-xt",
40 "--extension",
41 "-e",
42 "--model",
43 "--models",
44 "--name",
45 "-n",
46 "--prompt-template",
47 "--provider",
48 "--session-dir",
49 "--skill",
50 "--system-prompt",
51 "--theme",
52 "--thinking",
53 "--tools",
54 "-t",
55 "--tui-mode",
56 "--use-theme",
57]);
58​
59const PI_ARGUMENTS_WITHOUT_VALUES = new Set([
60 "--approve",
61 "-a",
62 "--no-approve",
63 "-na",
64 "--no-builtin-tools",
65 "-nbt",
66 "--no-context-files",
67 "-nc",
68 "--no-extensions",
69 "-ne",
70 "--no-prompt-templates",
71 "-np",
72 "--no-skills",
73 "-ns",
74 "--no-themes",
75 "--no-tools",
76 "-nt",
77 "--offline",
78 "--verbose",
79]);
80​
81export type PiLaunchArgsResolution =
82 | { readonly ok: true; readonly args: ReadonlyArray<string> }
83 | { readonly ok: false; readonly message: string };
84​
85function reservedPiArgument(arg: string): string | undefined {
86 for (const reserved of RESERVED_PI_LAUNCH_ARGUMENTS) {
87 if (arg === reserved || (reserved.startsWith("--") && arg.startsWith(`${reserved}=`))) {
88 return reserved;
89 }
90 }
91 return undefined;
93​
94function normalizePiBuiltInEqualsArguments(args: ReadonlyArray<string>): ReadonlyArray<string> {
95 return args.flatMap((arg) => {
96 const equalsIndex = arg.indexOf("=");
97 if (equalsIndex <= 0) return [arg];
98 const option = arg.slice(0, equalsIndex);
99 return PI_ARGUMENTS_WITH_VALUES.has(option) ? [option, arg.slice(equalsIndex + 1)] : [arg];
100 });
102​
103export function resolvePiLaunchArgs(launchArgs: string): PiLaunchArgsResolution {
104 // Pi parses equals-form tokens only as extension flags, even when their name
105 // matches a built-in option. Split known built-ins while leaving arbitrary
106 // extension flags in their native form.
107 const args = normalizePiBuiltInEqualsArguments(tokenizeCliArgs(launchArgs));
108 let hasProvider = false;
109 let hasModel = false;
110 for (let index = 0; index < args.length; index += 1) {
111 const arg = args[index];
112 if (arg === undefined) continue;
113 const reserved = reservedPiArgument(arg);
114 if (reserved !== undefined) {
115 return {
116 ok: false,
117 message: `Pi launch argument '${reserved}' is controlled by T3 Code and cannot be overridden.`,
118 };
119 }
120 if (arg === "--") {
121 return {
122 ok: false,
123 message: "Pi launch arguments cannot include positional prompts.",
124 };
125 }
126 if (PI_ARGUMENTS_WITH_VALUES.has(arg)) {
127 const value = args[index + 1];
128 if (value === undefined) {
129 return { ok: false, message: `Pi launch argument '${arg}' requires a value.` };
130 }
131 if (arg === "--provider") hasProvider = true;
132 if (arg === "--model") hasModel = true;
133 index += 1;
134 continue;
135 }
136 if (PI_ARGUMENTS_WITHOUT_VALUES.has(arg) || (arg.startsWith("--") && arg.includes("="))) {
137 continue;
138 }
139 if (arg.startsWith("--")) {
140 // Pi extensions may register arbitrary long flags. Treat one following
141 // non-flag token as that extension flag's value.
142 if (
143 args[index + 1] !== undefined &&
144 !args[index + 1]!.startsWith("-") &&
145 !args[index + 1]!.startsWith("@")
146 ) {
147 index += 1;
148 }
149 continue;
150 }
151 if (arg.startsWith("-")) {
152 return { ok: false, message: `Pi launch argument '${arg}' is not supported by T3 Code.` };
153 }
154 return {
155 ok: false,
156 message: `Pi launch arguments cannot include positional prompt '${arg}'.`,
157 };
158 }
159 if (hasProvider && !hasModel) {
160 return { ok: false, message: "Pi launch argument '--provider' requires '--model'." };
161 }
162 return { ok: true, args };
164​
165function bearerTokenFromAuthorizationHeader(header: string): string {
166 return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header;
168​
169function normalizedPiPath(value: string): string {
170 return value.replace(/\\/g, "/").replace(/\/+$/, "");
172​
173function hasExplicitExtension(args: ReadonlyArray<string>, extensionPath: string): boolean {
174 const wanted = normalizedPiPath(extensionPath);
175 for (let index = 0; index < args.length; index += 1) {
176 const arg = args[index];
177 if (arg !== "--extension" && arg !== "-e") continue;
178 const configured = args[index + 1];
179 if (configured !== undefined && normalizedPiPath(configured) === wanted) return true;
180 index += 1;
181 }
182 return false;
184​
185function withoutExplicitExtensions(args: ReadonlyArray<string>): ReadonlyArray<string> {
186 const filtered: string[] = [];
187 for (let index = 0; index < args.length; index += 1) {
188 const arg = args[index];
189 if (arg === undefined) continue;
190 if (arg === "--extension" || arg === "-e") {
191 index += 1;
192 continue;
193 }
194 if (arg.startsWith("--extension=") || arg.startsWith("-e=")) continue;
195 filtered.push(arg);
196 }
197 return filtered;
199​
200function withoutToolSelectionArgs(args: ReadonlyArray<string>): ReadonlyArray<string> {
201 const filtered: string[] = [];
202 for (let index = 0; index < args.length; index += 1) {
203 const arg = args[index];
204 if (arg === undefined) continue;
205 if (arg === "--tools" || arg === "-t" || arg === "--exclude-tools" || arg === "-xt") {
206 index += 1;
207 continue;
208 }
209 if (
210 arg === "--no-tools" ||
211 arg === "-nt" ||
212 arg === "--no-builtin-tools" ||
213 arg === "-nbt" ||
214 arg.startsWith("--tools=") ||
215 arg.startsWith("-t=") ||
216 arg.startsWith("--exclude-tools=") ||
217 arg.startsWith("-xt=")
218 ) {
219 continue;
220 }
221 filtered.push(arg);
222 }
223 return filtered;
225​
226function piT3McpExtensionDestPath(cacheDir: string): string {
227 return `${cacheDir.replace(/\\/g, "/")}/${PI_T3_MCP_EXTENSION_FILENAME}`;
229​
230export const materializePiT3McpExtension = Effect.fn("materializePiT3McpExtension")(function* (
231 cacheDir: string,
232) {
233 const fs = yield* FileSystem.FileSystem;
234 yield* fs.makeDirectory(cacheDir, { recursive: true });
235 const dest = piT3McpExtensionDestPath(cacheDir);
236 const existing = yield* fs.readFileString(dest).pipe(Effect.orElseSucceed(() => ""));
237 if (existing !== PI_T3_MCP_EXTENSION_SOURCE) {
238 yield* fs.writeFileString(dest, PI_T3_MCP_EXTENSION_SOURCE);
239 }
240 return dest;
241});
242​
243export function buildPiRpcLaunch(input: {
244 readonly launchArgs: ReadonlyArray<string>;
245 readonly environment: NodeJS.ProcessEnv;
246 readonly mcpSession: McpProviderSessionConfig | undefined;
247 readonly extensionPath: string | undefined;
248 readonly sessionPath?: string | undefined;
249 readonly ephemeral?: boolean;
250 readonly disableExtensions?: boolean;
251 readonly disableTools?: boolean;
252 readonly runtimeMode?: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
253}): {
254 readonly args: ReadonlyArray<string>;
255 readonly env: NodeJS.ProcessEnv;
256 readonly hasT3Mcp: boolean;
257} {
258 const hasT3Extension = input.disableExtensions !== true && input.extensionPath !== undefined;
259 const hasT3Mcp = hasT3Extension && input.mcpSession !== undefined;
260 const extensionSafeArgs =
261 input.disableExtensions === true
262 ? withoutExplicitExtensions(input.launchArgs)
263 : input.launchArgs;
264 const launchArgs =
265 input.disableTools === true ? withoutToolSelectionArgs(extensionSafeArgs) : extensionSafeArgs;
266 const args = [
267 "--mode",
268 "rpc",
269 ...(input.ephemeral === true
270 ? ["--no-session"]
271 : input.sessionPath !== undefined
272 ? ["--session", input.sessionPath]
273 : []),
274 ...launchArgs,
275 // Restrictions follow user launch args so a configured --tools or
276 // --extension cannot silently re-enable unattended text-generation code.
277 ...(input.disableExtensions === true ? ["--no-extensions"] : []),
278 ...(input.disableTools === true ? ["--no-tools"] : []),
279 ];
280 if (
281 hasT3Extension &&
282 input.extensionPath !== undefined &&
283 !hasExplicitExtension(args, input.extensionPath)
284 ) {
285 args.push("--extension", input.extensionPath);
286 }
287 const environment = { ...input.environment };
288 // These values belong to the current T3 session. Never let a Pi child reuse
289 // credentials inherited from the server or a parent provider process.
290 delete environment[T3_MCP_URL_ENV];
291 delete environment[T3_MCP_BEARER_ENV];
292 delete environment[T3_PI_MCP_EXTENSION_PATH_ENV];
293​
294 return {
295 args,
296 env: {
297 ...environment,
298 ...(hasT3Extension && input.extensionPath !== undefined
299 ? { [T3_PI_MCP_EXTENSION_PATH_ENV]: input.extensionPath }
300 : {}),
301 ...(hasT3Extension && input.runtimeMode !== undefined
302 ? {
303 [T3_PI_RUNTIME_MODE_ENV]:
304 input.runtimeMode === "auto" ? "approval-required" : input.runtimeMode,
305 }
306 : {}),
307 ...(hasT3Mcp && input.mcpSession !== undefined
308 ? {
309 [T3_MCP_URL_ENV]: input.mcpSession.endpoint,
310 [T3_MCP_BEARER_ENV]: bearerTokenFromAuthorizationHeader(
311 input.mcpSession.authorizationHeader,
312 ),
313 }
314 : {}),
315 },
316 hasT3Mcp,
317 };