Skip to main content
Glama
README.md
# TypeScript MCP Meta-Server

A Model Context Protocol (MCP) server that enables dynamic TypeScript scripting across multiple configured MCP servers.

## Outcome!
It worked really well, auto-gen and tests working, but MCP does not provide a return structure definition.  Therefor I cannot generate types for the return, as a result we are quite limited in terms of building a script that could cover nested or pipelined tool calls. 

It was a fun project that I vibecoded during evening tv. But I suspect this is the end of the project because the structure is insufficient to detect all the required info.  

*If I wanted to keep going:* On meta-server init I could try to run enough of the endpoints to auto detect the result.  AND / OR I could store the results somewhere and have this MCP learn / update it's types over time based on results.  

## Purpose

This MCP acts as a meta-layer that:
- Aggregates tools from multiple configured MCP servers
- Generates TypeScript definitions for all available tools
- Executes user-provided TypeScript scripts that can invoke any configured tool
- Provides a unified interface for multi-MCP orchestration

## Use Cases

- Compose complex workflows across multiple MCP servers
- Write reusable TypeScript scripts that leverage multiple tool ecosystems
- Dynamically discover and use tools without manual type definitions
- Enable LLMs to write and execute multi-tool scripts in a single operation

## Architecture

### Components

1. **Config Manager**: Loads and validates MCP server configurations
2. **MCP Client Pool**: Maintains connections to configured MCP servers
3. **Spec Generator**: Introspects tools and generates TypeScript definitions (using AWS Bedrock Claude if needed)
4. **Script Executor**: Compiles and runs user TypeScript scripts with tool access
5. **Tool Proxy**: Routes tool calls from scripts to appropriate MCP servers

### Design Considerations

**Tool Discovery**
- On startup, connect to all configured MCP servers
- Query each server's available tools via MCP protocol
- Cache tool schemas for definition generation

**TypeScript Definition Generation**
- Convert MCP tool schemas to TypeScript interfaces
- Generate a unified module with all tool functions
- Use AWS Bedrock Claude for complex schema transformations if direct mapping fails
- Include JSDoc comments with tool descriptions

**Script Execution Flow**
1. Receive TypeScript script from `run-script` tool
2. Inject tool proxy functions matching generated definitions
3. Compile TypeScript to JavaScript (using `ts-node` or `esbuild`)
4. Execute default export function
5. Capture tool calls and route to appropriate MCP servers
6. Return results or error summary to caller

**Error Handling**
- Compilation errors: Return TypeScript diagnostics
- Runtime errors: Capture stack traces and context
- Tool invocation errors: Include MCP server responses
- Use Bedrock to summarize complex error chains into actionable feedback

**Security**
- Sandbox script execution (consider VM2 or isolated worker threads)
- Validate tool calls against known schemas
- Timeout protection for long-running scripts
- No filesystem or network access from scripts (only via MCP tools)

## Implementation Task List

### Phase 1: Core Infrastructure
- [x] Initialize stdio MCP server boilerplate
- [x] Install required dependencies
- [x] Define configuration schema for MCP server list
- [x] Implement MCP client connection manager
- [x] Create tool discovery and caching system

### Phase 2: Spec Generation
- [x] Build MCP schema to TypeScript type converter
- [ ] Implement AWS Bedrock integration for complex schemas
- [x] Create `get-spec` tool that returns TypeScript definitions
- [x] Add caching and invalidation for generated specs

### Phase 3: Script Execution
- [x] Set up TypeScript compilation pipeline
- [x] Create tool proxy injection system
- [x] Implement `run-script` tool with script parameter
- [x] Build tool call router to target MCP servers

### Phase 4: Error Handling & Feedback
- [x] Capture and format compilation errors
- [x] Implement runtime error handling
- [x] Integrate Bedrock for error summarization
- [x] Add detailed logging and debugging output

### Phase 5: Testing & Documentation
- [x] Create example configurations
- [x] Write sample TypeScript scripts
- [ ] Add integration tests with mock MCP servers
- [x] Document configuration format and usage examples

### Phase 6: Optimization
- [ ] Add connection pooling and reuse
- [ ] Implement spec caching strategies
- [ ] Optimize script compilation (incremental builds)
- [ ] Add performance monitoring

## Configuration Format

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "..."
      }
    }
  }
}
```

## Tools Provided

### `get-spec`
Returns TypeScript definitions for all available tools from configured MCP servers.

**Returns**: String containing TypeScript module definition

### `run-script`
Executes a TypeScript script with access to all configured tools.

**Parameters**:
- `script`: TypeScript code with default export function `() => Promise<any>`

**Returns**: Script execution result or error summary

## Example Usage

```typescript
// Script provided to run-script tool
export default async function() {
  // Tools are injected based on configured MCPs
  const files = await filesystem.listDirectory({ path: "/src" });
  const issues = await github.listIssues({ repo: "owner/repo" });
  
  return {
    fileCount: files.length,
    openIssues: issues.filter(i => i.state === "open").length
  };
}
```

## Development

Install dependencies:
```bash
npm install
```

Build the server:
```bash
npm run build
```

For development with auto-rebuild:
```bash
npm run watch
```

## Testing

Run the integration test suite:
```bash
npm test
```

The test suite includes:
1. Server startup and tool discovery
2. TypeScript spec generation from MCP tools
3. Script compilation and execution
4. **Bedrock-powered script generation** - AI writes and executes scripts using available tools

### Prerequisites for Full Testing

**AWS Bedrock Access** (required for test 5):
1. Configure AWS credentials in `~/.aws/credentials`
2. Enable Bedrock model access in AWS Console:
   - Navigate to AWS Bedrock → Model access
   - Request access to: `Claude 3.5 Sonnet v2` (cross-region inference profile)
3. Ensure your AWS region supports Bedrock (e.g., `us-east-1`)

Without Bedrock access, test 5 will fail. Tests 1-4 will still pass and verify core functionality.

## Usage

1. Create a configuration file `mcp-config.json`:
```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
    }
  }
}
```

2. Set the config path (optional, defaults to `./mcp-config.json`):
```bash
export MCP_CONFIG_PATH=./mcp-config.json
```

3. Configure AWS credentials for Bedrock (optional, for error summarization):
```bash
export AWS_REGION=us-east-1
export AWS_ACCESS_KEY_ID=your-key
export AWS_SECRET_ACCESS_KEY=your-secret
```

4. Run the server:
```bash
node build/index.js
```

Or use with Claude Desktop by adding to your config:
```json
{
  "mcpServers": {
    "ts-mcp-meta": {
      "command": "node",
      "args": ["/path/to/ts-mcp/build/index.js"],
      "env": {
        "MCP_CONFIG_PATH": "/path/to/mcp-config.json"
      }
    }
  }
}
```

### Debugging

Since MCP servers communicate over stdio, debugging can be challenging. We recommend using the [MCP Inspector](https://github.com/modelcontextprotocol/inspector):

```bash
npm run inspector
```

The Inspector will provide a URL to access debugging tools in your browser.

## Dependencies

- `@modelcontextprotocol/sdk`: MCP protocol implementation
- `typescript`: TypeScript compiler
- `@aws-sdk/client-bedrock-runtime`: For AI-assisted spec generation
- `esbuild`: Script compilation
- `zod`: Configuration validation

## Future Enhancements

- Persistent script library
- Script versioning and history
- Parallel tool execution
- Streaming results for long-running scripts
- Web-based script editor and debugger