Labsco
zbowling logo

mcpcodeserver

13

from zbowling

Instead of direct calling MCP tools, mcpcode server transforms MCP tool calls into TypeScript programs, enabling smarter, lower-latency orchestration by LLMs.

🔥🔥🔥🔥✓ VerifiedFreeNeeds API keys

mcpcodeserver

Install MCP Server Install in VS Code (npx)

A Model Context Protocol (MCP) proxy server that translates tool calls into TypeScript code generation. Instead of making multiple tool calls back and forth, LLMs can write TypeScript code that calls multiple tools naturally, reducing token overhead and leveraging the LLM's superior code generation capabilities.

❌ Without mcpcodeserver

LLMs make multiple sequential tool calls, burning tokens and struggling with complex workflows:

  • ❌ Multiple round-trips between LLM and tools
  • ❌ Complex tool calling sequences are error-prone
  • ❌ Data cannot easily be passed between tools
  • ❌ Limited error handling and control flow

✅ With mcpcodeserver

LLMs write TypeScript code that calls multiple tools naturally:

  • ✅ Write code to call multiple tools in sequence
  • ✅ Use variables, loops, and conditionals naturally
  • ✅ Better error handling with try/catch
  • ✅ Reduce token usage by combining operations
  • ✅ Leverage LLM's strong code generation capabilities

Overview

mcpcodeserver is a unique MCP server that:

  • Acts as an MCP client to connect to one or more child MCP servers
  • Discovers all tools from child servers
  • Exposes three powerful tools to parent LLM clients:
    1. list_servers - Lists all available sub-servers connected to this MCP server
    2. get_tool_definitions - Returns TypeScript type definitions for discovered tools (optionally filtered by server)
    3. generate_and_execute_code - Generates and executes TypeScript code that calls those tools in a sandbox

This architecture allows LLMs to orchestrate complex multi-tool workflows by writing code instead of making sequential tool calls, which is often more efficient and natural for modern language models.

This approach is inspired by recent research showing that LLMs perform better when generating executable code rather than making direct tool calls:

  • CodeAct: Your LLM Agent Acts Better when Generating Code (Apple, ICML 2024) - Demonstrates that LLM agents achieve up to 20% higher success rates when using executable Python code as a unified action space instead of pre-defined tool calling formats.

  • Cloudflare Code Mode - A similar implementation that converts MCP tools into TypeScript APIs, showing that "LLMs are better at writing code to call MCP, than at calling MCP directly."

The key insight from this research is that LLMs have extensive training on real-world code but limited exposure to synthetic tool-calling formats, making code generation a more natural and effective approach for complex agent workflows.

Why Use This?

Traditional Tool Calling Problems

  • Multiple round-trips between LLM and tools burn tokens
  • LLMs often struggle with complex tool calling sequences
  • Each tool call requires JSON schema understanding and formatting
  • Data cannot easily be passed between tools without going through the LLM

Code Generation Solution

  • Write TypeScript code to call multiple tools in sequence
  • Use variables, loops, and conditionals naturally
  • Better error handling with try/catch
  • Reduce token usage by combining operations
  • Leverage LLM's strong code generation capabilities

Dynamic Tool Discovery

mcpcodeserver automatically monitors child MCP servers for tool changes and notifies parent clients when tools are added, removed, or modified:

  • Automatic Refresh: Checks for tool changes every 30 seconds
  • Real-time Notifications: Sends notifications/tools/list_changed to parent clients
  • Dynamic Updates: Tool definitions and summaries update automatically
  • No Manual Refresh: Parent LLMs receive notifications to refresh their tool knowledge

This ensures that parent LLMs always have the most current tool definitions without requiring manual intervention.

Server Filtering

To reduce context window usage and improve focus, mcpcodeserver supports filtering tool definitions by specific servers:

  • List Available Servers: Use list_servers to see all connected sub-servers
  • Filtered Tool Definitions: Use get_tool_definitions with server_names parameter to get tools from specific servers only
  • Reduced Verbosity: Get focused TypeScript definitions without overwhelming the LLM's context window
  • Method Namespacing: All generated functions are prefixed with server names (e.g., pizzashop_create_pizza, filesystem_read_file)

Example usage:

// List available servers
const servers = await list_servers({});
// Returns: ["pizzashop", "filesystem", "memory"]

// Get all tool definitions
const allTools = await get_tool_definitions({});

// Get only pizzashop tools
const pizzashopTools = await get_tool_definitions({
  server_names: ["pizzashop"]
});

Advanced MCP Features

mcpcodeserver supports pass-through of advanced MCP protocol features when both parent and child servers support them:

  • Elicitation: Child servers can request user input during tool execution, which is passed through to parent clients
  • Roots: Lists and aggregates roots from all child servers, providing a unified view of available resources
  • Sampling: Enables LLM sampling requests to be passed through to child servers for advanced AI capabilities

These features are automatically advertised to parent clients and work seamlessly when supported by the underlying child MCP servers.

💻 Development

CLI Arguments

mcpcodeserver accepts the following CLI flags:

  • --config <path> – Path to the MCP configuration file (default: ./mcp.json)
  • --transport <stdio|http> – Transport to use (stdio by default). Note that HTTP transport automatically provides both HTTP and SSE endpoints
  • --port <number> – Port to listen on when using http transport (default 3000)
  • --help – Show help message

Example with HTTP transport and port 8080:

npx mcpcodeserver --config /path/to/mcp.json --transport http --port 8080

Example with stdio transport:

npx mcpcodeserver --config /path/to/mcp.json --transport stdio

Environment Variables

You can use environment variables for configuration:

  • MCP_CONFIG_PATH – Path to the MCP configuration file (alternative to --config)
  • MCP_TRANSPORT – Transport type (alternative to --transport)
  • MCP_PORT – Port number for HTTP transport (alternative to --port)

Example with environment variables:

# .env
MCP_CONFIG_PATH=/path/to/your/mcp.json
MCP_TRANSPORT=stdio

Example MCP configuration using environment variables:

{
  "mcpServers": {
    "mcpcodeserver": {
      "command": "npx",
      "args": ["-y", "mcpcodeserver"],
      "env": {
        "MCP_CONFIG_PATH": "/path/to/your/mcp.json"
      }
    }
  }
}

Note: CLI flags take precedence over environment variables when both are provided.

Local Development Configuration

For local development, you can run the TypeScript source directly:

{
  "mcpServers": {
    "mcpcodeserver": {
      "command": "npx",
      "args": ["tsx", "/path/to/mcpcodeserver/src/index.ts", "--config", "/path/to/your/mcp.json"]
    }
  }
}

Sandbox Environment

The TypeScript execution sandbox provides:

Available:

  • All discovered tool functions (as async functions)
  • Console methods: console.log(), console.error(), console.warn(), console.info()
  • Basic JavaScript globals: Math, JSON, Date, Array, Object, String, Number, Boolean
  • Promise and async/await support
  • Error handling with try/catch
  • Timers: setTimeout, setInterval, clearTimeout, clearInterval

Not Available:

  • Node.js modules (fs, http, child_process, etc.)
  • File system access (except via MCP tools)
  • Network access (except via MCP tools)
  • Process information

Security Note: This is not a fully secure sandbox. The VM context provides isolation but is not bulletproof. Only execute trusted code.

Error Handling

Errors in the sandbox are caught and returned with stack traces:

generate_and_execute_code({
  code: `
    try {
      const result = await filesystem_read_file({ path: "/nonexistent" });
      return result;
    } catch (error) {
      console.error("Failed to read file:", error.message);
      throw error; // Re-throw to surface to parent
    }
  `
})

Testing with Claude Code

Want to try mcpcodeserver with Claude Code? Use the one-command setup:

./setup-claude-code-test.sh

This will build the project, install test dependencies, and show you exactly what to add to your Claude Code configuration. See TESTING_WITH_CLAUDE.md for detailed instructions.

Development

# Install dependencies
bun install

# Build the project
bun run build

# Watch mode for development
bun run dev

# Run the server
bun start

# Run tests
bun test                # All tests
bun run test:unit       # Unit tests only
bun run test:integration # Integration tests (requires Python)

# Code quality
bun run lint            # Check linting
bun run format          # Format code
bun run typecheck       # Type checking

Project Structure

See AGENTS.md for detailed project structure and component documentation.

Use Cases

Multi-File Operations

Instead of making multiple tool calls through the LLM, write code:

const files = ["/tmp/a.txt", "/tmp/b.txt", "/tmp/c.txt"];
const contents = await Promise.all(
  files.map(path => filesystem_read_file({ path }))
);
return contents.map(r => r.content[0].text);

Data Transformation

Process data between tool calls without LLM intervention:

const data = await api_fetch({ url: "https://api.example.com/data" });
const json = JSON.parse(data.content[0].text);
const filtered = json.items.filter(item => item.active);
return filtered.length;

Conditional Logic

Make decisions based on tool results:

const exists = await filesystem_read_file({ path: "/tmp/config.json" });
if (exists.isError) {
  console.log("Config doesn't exist, using defaults");
  return { source: "defaults" };
} else {
  return { source: "file", config: JSON.parse(exists.content[0].text) };
}

Error Recovery

Handle errors gracefully without aborting the entire workflow:

const results = [];
for (const path of ["/tmp/a.txt", "/tmp/b.txt", "/tmp/c.txt"]) {
  try {
    const content = await filesystem_read_file({ path });
    results.push({ path, success: true, data: content });
  } catch (error) {
    results.push({ path, success: false, error: error.message });
  }
}
return results;

Upstream MCP Servers Integration

mcpcodeserver can integrate with official upstream MCP servers from the Model Context Protocol servers repository. This allows you to use real, production-ready MCP servers alongside your custom tools.

Supported Upstream Servers

  • filesystem: File system operations (read, write, list directories)
  • memory: In-memory key-value storage
  • sqlite: SQLite database operations
  • github: GitHub API integration
  • brave-search: Web search capabilities
  • fetch: HTTP request capabilities

Example Configuration

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
    },
    "memory": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"]
    },
    "sqlite": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-sqlite", "--db-path", "/tmp/test.db"]
    }
  }
}

Testing Upstream Integration

The project includes comprehensive tests for upstream server integration:

# Run upstream servers integration tests
bun tests/integration/run-upstream-tests.ts

# Or manually test with upstream config
npx mcpcodeserver --config tests/integration/upstream-test-config.json

Cross-Server Workflows

With upstream servers, you can create powerful cross-server workflows:

// Store database query results in memory and write to file
const queryResult = await sqlite_execute_sql({
  sql: "SELECT COUNT(*) as count FROM users"
});
const count = queryResult.content[0].text;

await memory_create({
  key: "user-count",
  value: count
});

await filesystem_write_file({
  path: "/tmp/user-count.txt",
  content: `Total users: ${count}`
});

Support

If you find this project helpful, consider buying me a coffee!

Resources