Sponsored by Deepsite.site

mcp-runner

Created By
cookiecada year ago
A TypeScript SDK for running MCP (Model Context Protocol) servers with process reuse capabilities
Content

mcp-runner

A TypeScript SDK and CLI for running MCP (Model Context Protocol) servers.

Overview

mcp-runner is designed to facilitate the execution of MCP servers based on configurations defined in cline_mcp_settings.json. It supports reusable server processes and controlled cleanup, allowing multiple operations to be performed using the same server instance.

You can call it from the command line or use it as a library in your own TypeScript projects or even from other MCP servers.

Features

  • Server process reuse across multiple calls
  • Graceful termination with timeout handling
  • Automatic server lifecycle management
  • TypeScript support
  • Error handling and logging

Installation

npm install

CLI Usage

The package includes a command-line interface for interacting with MCP servers.

Commands

List Tools

Lists all available tools for a specified MCP server:

npm run cli -- list-tools <server-name>

Example:

npm run cli -- list-tools sequential-thinking

Run Server

Runs a specified MCP server with optional tool name and parameters:

npm run cli -- runserver <server-name> [tool-name] [params] [options]
# or
npm run cli -- runserver <server-name> [params] [options] # uses first available tool

Options:

  • --text: Output only the text content from the response instead of the full JSON

Examples:

# Run a specific tool
npm run cli -- runserver sequential-thinking sequentialthinking '{"thought": "Initial thought", "thoughtNumber": 1, "totalThoughts": 5, "nextThoughtNeeded": true}'

# Use first available tool
npm run cli -- runserver sequential-thinking '{"thought": "Initial thought", "thoughtNumber": 1, "totalThoughts": 5, "nextThoughtNeeded": true}'

# Output only text content
npm run cli -- runserver sequential-thinking sequentialthinking '{"thought": "Initial thought", "thoughtNumber": 1, "totalThoughts": 1}' --text

Programmatic Usage

Basic Example

import { runServer, terminateServer } from 'mcp-runner';

async function main() {
  try {
    // First call (specific tool)
    const result1 = await runServer('openrouterai', 'chat_completion', {
      messages: [
        { role: 'user', content: 'Say hello!' }
      ]
    });
    console.log('Result 1:', result1);

    // Second call (uses first available tool)
    const result2 = await runServer('openrouterai', undefined, {
      messages: [
        { role: 'user', content: 'How are you?' }
      ]
    });
    console.log('Result 2:', result2);

    // Terminate server when done
    await terminateServer();
  } catch (error) {
    console.error('Error:', error);
    await terminateServer();
  }
}

Error Handling

The SDK includes comprehensive error handling:

  • Server process errors
  • Tool execution errors
  • Timeout handling for graceful termination
  • Automatic cleanup on errors

API

runServer(serverName: string, params: Record<string, unknown>)

Runs a tool on the specified server using provided parameters. The server process is reused for subsequent calls until explicitly terminated.

Parameters:

  • serverName: Name of the server from configuration
  • params: Parameters to pass to the server's tool

Returns: Promise resolving with the server's response

terminateServer()

Terminates the server process managed by the SDK. Should be called when all operations are complete.

Returns: Promise that resolves when the server is terminated

Architecture

ServerManager

The ServerManager class is implemented as a singleton that manages the lifecycle of MCP server processes. Key responsibilities include:

  • Process lifecycle management
  • Client connection handling
  • Graceful termination
  • Error handling and logging

The manager ensures that only one server process is running at any given time and provides methods to start, reuse, and terminate the server.

Configuration

The SDK reads server configurations from cline_mcp_settings.json, which should be located in the standard configuration directory. Each server configuration includes:

{
  "command": "string",
  "args": "string[]",
  "env": "Record<string, string>",
  "disabled": "boolean",
  "alwaysAllow": "string[]"
}

Development

Building

npm run build

Running Tests

npm test

License

This project is licensed under the Mozilla Public License 2.0 - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Tavily Mcp
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Playwright McpPlaywright MCP server
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Serper MCP ServerA Serper MCP Server
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Amap Maps高德地图官方 MCP Server
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
CursorThe AI Code Editor
ChatWiseThe second fastest AI chatbot™
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
WindsurfThe new purpose-built IDE to harness magic
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
DeepChatYour AI Partner on Desktop
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors