feat(client): Built-in WASM Script Client + Auto .d.ts Return Type Inference (Solving Missing outputSchema in Code Mode)
Les mainteneurs répondent en général sous 1 jour
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Accessibilité débutants
- 15/100
- Type d'issue
- Fonctionnalité
- Clarté
- Clairement spécifiée
- Activité
- Active
- Stack technique
- node.js, typescript, wasm
Piste de recherche
Start by reading the TypeScript SDK's client tool handling and tool definition types, then assess how the proposed script execution, type inference, and metadata extension fit those entry points. The issue describes a broad client SDK and protocol design; done would require a reviewed design and working implementation covering sandboxing, tool calls, declarations, and tests.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
Solving Missing Return Types in MCP Code Mode via _meta.tsReturnType, Client-Side Auto .d.ts Inference & Built-in WASM Script Client
- Status: Proposal
- Type: Standards Track (Client SDK & Tool Metadata Extension)
- Created: 2026-11-09
1. Abstract & Core Idea (LLM-Generated One-Time Script per Tool Call)
The Core Workflow:
Instead of the LLM making multiple static tools/call requests and receiving huge raw JSON responses into its context window, the MCP Client exposes the connected MCP tools as compact TypeScript interfaces (declare namespace sdk { ... }) and provides a single tool (execute_mcp_script). Using those TypeScript interfaces, the LLM dynamically writes and sends a custom, one-time JavaScript/TypeScript function (async (sdk) => { ... }) in a single tool call to:
- Call one or more MCP tools (including sequential dependent calls where
Tool Buses the output ofTool A), - Manipulate, filter, join, and aggregate the raw responses in-flight using custom logic, and
- Return only the final distilled result back to the LLM context window.
Solving the Two Blockers (Security & Missing Return Types):
- Zero-Trust Client-Side Execution (Solving Server Secret Risk): Because an LLM can generate arbitrary code, running that script on the MCP Server would risk exposing server variables and
process.envsecrets. By executing the LLM-generated script on the MCP Client inside a disposable QuickJS WebAssembly sandbox (quickjs-emscripten) with only thesdkproxy injected, server secrets are 100% unreachable and zero server changes are required. - TypeScript Return Interfaces (
_meta.tsReturnType& Auto-Inference): For the LLM to write working response-manipulation code on the first try, it must know the exact TypeScript structure of the tool's response. Because 95%+ of existing MCP servers omitoutputSchema(which results inPromise<unknown>), this proposal introduces optional_meta.tsReturnTypemetadata plus automatic Client-side.d.tsreturn-type inference from live JSON responses.
2. Motivation
Standard MCP tool invocation suffers from four compounding bottlenecks in production host applications (such as Claude Code, Claude Desktop, Cursor, and IDE agents):
- Context Window Bloating (Data Moves to Compute):
Calling a data-fetching tool (e.g.,listCustomers,listIssues,queryLogs) dumps tens or hundreds of kilobytes of raw JSON directly into the LLM context window, even when the model only needs a filtered subset or aggregate count. - Multi-Turn Dependent Call Latency & Context Re-Billing:
WhenTool Brequires an ID or field fromTool A's output (Tool A -> Tool B -> Tool C), standard MCP requires a full LLM inference round-trip between every step—re-billing the entire conversation history on each turn. - Missing Output Type Definitions on 95%+ of Existing MCP Servers:
While MCP supports optionaloutputSchema, the vast majority of deployed MCP servers omit it and return serialized JSON insidecontent[0].text. Without knowing the exact return shape upfront, an LLM cannot reliably write a single-pass transformation script. - Server-Side Execution Security Risks:
Executing LLM-generated scripts on the MCP Server exposes server secrets (process.env, DB credentials, internal networks) unless every server author deploys heavy isolation infrastructure.
By placing a Zero-Trust WASM Sandbox and Automatic .d.ts Type Inferrer inside the MCP Client / Host Application layer, every existing MCP server gains >98% token reduction and single-turn multi-server orchestration with zero server modifications and zero server secret exposure.
3. Specification & Architecture
3.1. Tool Metadata Extension (_meta.tsReturnType) & Client Auto-Inference
- Explicit TypeScript Return Type (Optional Server Metadata):
MCP Servers MAY attach_meta.tsReturnType(a compact TypeScript type string) or standardoutputSchemato tool definitions intools/list:{ "name": "getCustomerById", "inputSchema": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] }, "_meta": { "tsReturnType": "{ id: string; name: string; tier: 'enterprise' | 'pro' | 'free'; active: boolean } | null" } } - Client-Side Automatic
.d.tsInference (Fallback for Existing MCP Servers):
When an upstream tool omits both_meta.tsReturnTypeandoutputSchema, the MCP Client inspects the first JSON response returned bytools/call, infers its TypeScript structural interface automatically, and caches the resulting.d.tssignature for subsequent turns.
3.2. Client-Generated Ambient TypeScript Declarations (declare namespace sdk)
The MCP Client aggregates all connected MCP servers into a single compact .d.ts declaration block:
declare namespace sdk {
namespace crm {
function listCustomers(args?: { includeInactive?: boolean }): Promise<Array<{ id: string; name: string; tier: 'enterprise' | 'pro' | 'free'; region: string; active: boolean }>>;
function getCustomerById(args: { id: string }): Promise<{ id: string; name: string; tier: string; active: boolean } | null>;
}
namespace billing {
function listInvoices(args?: { status?: "paid" | "overdue" | "draft" }): Promise<Array<{ invoiceId: string; customerId: string; amountUsd: number; status: string }>>;
}
}
3.3. Client-Side Zero-Trust WASM Execution (McpScriptClient.executeScript)
When the LLM invokes execute_mcp_script, the MCP Client:
- Instantiates a disposable QuickJS WebAssembly runtime (
quickjs-emscripten) with a strict memory cap (default:16 MB) and CPU deadline interrupt handler (default:500 ms). - Injects only a frozen capability proxy object (
sdk.<server>.<tool>). The WASM linear memory contains noprocess,env,fs,require,fetch, or shared V8 prototype chain with the host. - Executes the LLM's
async (sdk) => { ... }function:- Parallel calls (
await Promise.all([sdk.crm.listCustomers(), sdk.billing.listInvoices()])) and sequential dependent chains (Tool A -> output -> Tool B) resolve inside the sandbox via standard MCPclient.callTool()calls on the host. - Raw JSON responses are parsed inside WASM memory, filtered/joined/reduced by the script, and immediately freed when the WASM context is disposed.
- Parallel calls (
- Returns only the final serialized return value to the LLM context window.
3.4. End-to-End Example (Dependent Tool Chaining + Filtering in 1 Turn)
Instead of 3 sequential LLM turns dumping 300 KB of raw JSON into the context window, the LLM submits a single execute_mcp_script call:
async (sdk) => {
// Step 1: Fetch customers and filter in-memory inside WASM sandbox
const allCustomers = await sdk.crm.listCustomers({ includeInactive: true });
const target = allCustomers.find(c => !c.active && c.tier === "enterprise");
if (!target) return null;
// Step 2: Dependent call on the same MCP server using `target.id` from Step 1
const verifiedCustomer = await sdk.crm.getCustomerById({ id: target.id });
// Step 3: Cross-server join with billing invoices
const overdue = await sdk.billing.listInvoices({ status: "overdue" });
const customerOverdue = overdue.filter(inv => inv.customerId === verifiedCustomer.id);
// Only this compact object (~150 bytes) is returned to the LLM context window
return {
customerId: verifiedCustomer.id,
customerName: verifiedCustomer.name,
overdueCount: customerOverdue.length,
overdueTotalUsd: customerOverdue.reduce((sum, i) => sum + i.amountUsd, 0)
};
}
4. Security Analysis
All untrusted code runs exclusively inside the MCP Client's disposable QuickJS WebAssembly linear memory space:
| Threat Vector | Mitigation | Verified Outcome |
|---|---|---|
MCP Server Secret Leakage (process.env) |
Script executes on the MCP Client inside WASM; upstream MCP servers only receive standard JSON-RPC tools/call requests. |
ReferenceError: 'process' is not defined |
Prototype Chain Escape (constructor.constructor) |
Separate WASM heap; no shared V8 objects or prototypes with the Node.js host process. | ReferenceError: 'process' is not defined |
Filesystem / OS Access (fs, child_process) |
No WASI filesystem or OS imports mounted into the QuickJS WASM module. | ReferenceError: 'require' is not defined |
Data Exfiltration (fetch, sockets) |
Zero network bindings inside the WASM runtime. | ReferenceError: 'fetch' is not defined |
CPU / Memory Denial of Service (while(true){}) |
Enforced runtime.setMemoryLimit() and shouldInterruptAfterDeadline() interrupt handler. |
InternalError: interrupted at deadline |
5. Benchmark Results (Reference Implementation)
Evaluated on a multi-server task joining 500 CRM customer records (crm MCP server) with 1,500 billing invoice records (billing MCP server) plus a 3-step sequential dependent lookup (listCustomers -> getCustomerById -> listInvoices):
| Metric | Standard MCP | Client-Side Script Mode | Improvement |
|---|---|---|---|
| LLM Tool Call Round-Trips | 3 sequential turns | 1 single turn | 3x fewer turns |
| Raw Payload Entered into LLM Context | 305,711 bytes | 1,168 bytes | 99.62% reduction |
Total LLM Context Tokens (incl. .d.ts + script) |
~76,428 tokens | ~965 tokens | 98.74% token savings |
Dependent Chain (Tool A -> Tool B -> Tool C) |
3 LLM turns | 1 LLM turn (15.6 ms local) | Eliminates 2 full context re-sends |
6. Backward Compatibility
- 100% Backward-Compatible with Existing MCP Servers: Requires zero changes to deployed MCP servers.
- Hybrid or Pure Exposure in Host Apps: Host applications (Claude Code, Claude Desktop, etc.) can expose
execute_mcp_scriptalongside standard tools (Hybrid Mode) or replace raw tool schemas with compact.d.tsdeclarations when tool counts or payload sizes exceed a threshold.
- Langage dominant
- TypeScript
- Étoiles
- 13.8k
- Forks
- 2.5k
- Merge moyen
- 6 j 23 h
- PR mergées (30 j)
- 2
Préparer son environnement
- Aucun Dockerfile ni fichier Docker Compose
- Aucun modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de modelcontextprotocol/typescript-sdk
-
v2
Difficulté 1/5 Moins d'une heure Accessibilité débutants 72/100
modelcontextprotocol/typescript-sdk#3270 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
`callTool` with `allowInputRequired: true` throws on an `input_required` result when the tool declares an `outputSchema`Peut-être pris @mgoldsborough l’a pris il y a 6 jours. Ouvertev2
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
modelcontextprotocol/typescript-sdk#3249 ·
Les mainteneurs répondent en général sous 1 jour
-
v2
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
modelcontextprotocol/typescript-sdk#3243 · 3 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
TypeScript client accepts an unknown `resultType` in the first `server/discover` replyPeut-être pris @Tidehyc l’a pris il y a 7 jours. Ouvertev2
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
modelcontextprotocol/typescript-sdk#3235 · 3 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
UriTemplate.match() throws a TypeError on an empty expression it acceptsPeut-être pris @yunusemrejs l’a pris il y a 12 jours. Ouvertev1 v2
Difficulté 2/5 1-3 heures Accessibilité débutants 80/100
modelcontextprotocol/typescript-sdk#3221 · 3 commentaires ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de modelcontextprotocol/typescript-sdk
Issues similaires
-
bug
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
-
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
Vessel9817/onion-site-template#512 ·
Les mainteneurs répondent en général sous 1 jour
-
nightly-tests
Difficulté 2/5 1-3 heures Accessibilité débutants 68/100
BlackBeltTechnology/pi-agent-dashboard#1256 ·
Les mainteneurs répondent en général sous 1 jour
-
approved
Difficulté 2/5 1-3 heures Accessibilité débutants 85/100
fritzprix/libr-agent#3266 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 1/5 Moins d'une heure Accessibilité débutants 88/100
better-auth/better-auth#13101 · 1 commentaire · 1 réaction ·
Les mainteneurs répondent en général sous 1 jour