npm package: @migrateforce/mcp
Description: REST API to MCP (Model Context Protocol) server code generator. Transform OpenAPI specs into AI-consumable MCP endpoints.
Author: MigrateForce
Latest version: 0.1.0

# @migrateforce/mcp

> REST API to MCP (Model Context Protocol) server code generator.
> Transform OpenAPI specs into AI-consumable MCP endpoints.

[![npm version](https://badge.fury.io/js/@migrateforce/mcp.svg)](https://www.npmjs.com/package/@migrateforce/mcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## What is MCP?

**MCP (Model Context Protocol)** is a standardized interface that allows AI agents to discover and execute API operations. Instead of requiring custom integrations for each API, agents can:

1. **Discover** available tools via `GET /mcp`
2. **Execute** tools via `POST /mcp` with standardized payloads
3. **Understand** tool semantics through schema and descriptions

This library generates complete, runnable MCP servers from your OpenAPI specifications.

## Installation

```bash
npm install @migrateforce/mcp
# or
yarn add @migrateforce/mcp
# or
pnpm add @migrateforce/mcp
```

## Quick Start

### Parse an OpenAPI Spec

```typescript
import { parseOpenApiSpec, extractEndpointsFromSpec } from '@migrateforce/mcp'

const spec = await parseOpenApiSpec(yourOpenApiYamlOrJson)
const endpoints = extractEndpointsFromSpec(spec)

console.log(`Found ${endpoints.length} endpoints`)
```

### Generate an MCP Server

```typescript
import { generateMcpServer } from '@migrateforce/mcp'

const server = generateMcpServer({
  projectName: 'My API',
  projectDescription: 'MCP server for My API',
  targetApiBaseUrl: 'https://api.example.com',
  openApiSpec: parsedSpec,
  mappings: [
    {
      id: 'get-users',
      rest_api_path: '/users',
      rest_api_method: 'GET',
      mcp_tool_name: 'list_users',
      mcp_tool_description: 'Lists all users in the system',
      is_included: true,
    },
    // ... more mappings
  ],
})

// server.mainPy       - Python FastAPI server code
// server.dockerfile   - Docker configuration
// server.requirementsTxt - Python dependencies
// server.readme       - Documentation
// server.manifest     - MCP manifest JSON
```

### Lint Your OpenAPI Spec

```typescript
import { lintOpenApiSpec } from '@migrateforce/mcp'

const { lintResults, advice } = await lintOpenApiSpec(yourSpec)

for (const result of lintResults) {
  console.log(`[${result.severity}] ${result.path} ${result.method}: ${result.message}`)
}

for (const tip of advice) {
  console.log(`Tip: ${tip}`)
}
```

## API Reference

### OpenAPI Parsing

| Function | Description |
|----------|-------------|
| `parseOpenApiSpec(content)` | Parse and dereference an OpenAPI spec |
| `validateOpenApiSpec(content)` | Validate without full parsing |
| `extractEndpointsFromSpec(spec)` | Extract all endpoints |
| `getEndpointSchemaInfo(spec, path, method)` | Get detailed schema for an endpoint |
| `lintOpenApiSpec(content)` | Lint and get advice for MCP generation |
| `generateToolName(endpoint)` | Generate a tool name from endpoint |

### Code Generation

| Function | Description |
|----------|-------------|
| `generateMcpServer(options)` | Generate complete MCP server package |

## Generated Server Features

The generated MCP server includes:

- **FastAPI-based Python server** with async support
- **Tool discovery endpoint** (`GET /mcp`)
- **Tool execution endpoint** (`POST /mcp`)
- **Health check** (`GET /_mcp_health`)
- **Interactive API docs** (`GET /_mcp_docs`)
- **Docker support** with non-root user
- **Environment configuration** for target API URL
- **Authorization passthrough** for secure APIs
- **Role-based access control** support

## Output Structure

```
generated/
├── main.py           # FastAPI server with tool handlers
├── Dockerfile        # Production-ready container config
├── requirements.txt  # Python dependencies
├── README.md         # Usage documentation
├── .env.example      # Environment variable template
└── mcp-manifest.json # Tool definitions for discovery
```

## Tool Mapping Options

```typescript
interface McpToolMapping {
  id: string
  rest_api_path: string           // e.g., '/users/{id}'
  rest_api_method: HttpMethod     // GET, POST, PUT, DELETE, etc.
  mcp_tool_name: string           // Generated tool name
  mcp_tool_description?: string   // Description for AI agents
  is_included: boolean            // Include in generation?
  python_pre_request_snippet?: string   // Code to run before API call
  python_post_response_snippet?: string // Code to run after response
}
```

## Example: Full Workflow

```typescript
import { 
  parseOpenApiSpec, 
  extractEndpointsFromSpec,
  generateToolName,
  generateMcpServer 
} from '@migrateforce/mcp'
import fs from 'fs'

// 1. Parse OpenAPI spec
const specContent = fs.readFileSync('openapi.yaml', 'utf-8')
const spec = await parseOpenApiSpec(specContent)

// 2. Extract and map endpoints
const endpoints = extractEndpointsFromSpec(spec)
const mappings = endpoints.map(ep => ({
  id: `${ep.method}-${ep.path}`,
  rest_api_path: ep.path,
  rest_api_method: ep.method,
  mcp_tool_name: generateToolName(ep),
  mcp_tool_description: ep.summary || ep.description,
  is_included: true,
}))

// 3. Generate MCP server
const server = generateMcpServer({
  projectName: 'Petstore API',
  targetApiBaseUrl: 'https://petstore.swagger.io/v2',
  openApiSpec: spec,
  mappings,
})

// 4. Write output files
fs.writeFileSync('output/main.py', server.mainPy)
fs.writeFileSync('output/Dockerfile', server.dockerfile)
fs.writeFileSync('output/requirements.txt', server.requirementsTxt)
fs.writeFileSync('output/README.md', server.readme)
fs.writeFileSync('output/mcp-manifest.json', JSON.stringify(server.manifest, null, 2))
```

## Integration with MigrateForce Skills

This package pairs with [@migrateforce/skills](https://www.npmjs.com/package/@migrateforce/skills):

- **MCP** = How to do it (tools, actions, API calls)
- **Skills** = What to do (knowledge, context, playbooks)

Together they enable agents to execute complete migration workflows.

## Contributing

We welcome contributions! Please see our [Contributing Guide](https://github.com/sprotolabs/migrateforce-mcp/blob/main/CONTRIBUTING.md).

## License

MIT © [MigrateForce](https://migrateforce.com)