# MCP Server Quickstart

A minimal, well-documented Model Context Protocol (MCP) server template. Use this as a starting point to build your own MCP tools.

## What is MCP?

The [Model Context Protocol](https://modelcontextprotocol.io/) is an open standard that lets AI assistants (like Claude or Cursor) use external tools. Think of it like giving Claude hands to interact with the world:

```
┌─────────────┐     MCP Protocol      ┌─────────────┐
│     AI      │ ◄──────────────────►  │ Your Server │
│  (Client)   │   JSON-RPC over       │   (Tools)   │
└─────────────┘      stdio            └─────────────┘
```

**Key concepts:**
- **Server**: Your code that exposes tools (this repo)
- **Client**: The AI assistant that calls your tools (Cursor, Claude Code, etc.)
- **Tools**: Functions the AI can invoke with structured inputs/outputs
- **Transport**: How client and server communicate (usually stdio)

## Quick Start

### 1. Clone and Install

```bash
git clone https://github.com/fellanH/klar-mcp.git
cd klar-mcp
npm install
```

### 2. Build

```bash
npm run build
```

### 3. Configure Your Client

Add this server to your MCP client configuration:

<details>
<summary><strong>Claude Desktop</strong></summary>

Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

```json
{
  "mcpServers": {
    "klar-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/klar-mcp/dist/index.js"]
    }
  }
}
```
</details>

<details>
<summary><strong>Claude Code</strong></summary>

Run:
```bash
claude mcp add klar-mcp node /absolute/path/to/klar-mcp/dist/index.js
```
</details>

<details>
<summary><strong>Cursor</strong></summary>

1. Open Cursor Settings (`Cmd+,` on macOS, `Ctrl+,` on Windows/Linux)
2. Search for "MCP" or navigate to **Features > MCP Servers**
3. Click **Add new MCP server**
4. Enter:
   - **Name**: `klar-mcp`
   - **Type**: `command`
   - **Command**: `node /absolute/path/to/klar-mcp/dist/index.js`

Or edit `~/.cursor/mcp.json` directly:
```json
{
  "mcpServers": {
    "klar-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/klar-mcp/dist/index.js"]
    }
  }
}
```
</details>

### 4. Test

Restart your client (Claude Desktop, Claude Code, or Cursor). You should now be able to ask the AI to use your tools:

> "Use the hello_world tool to greet me"

## Project Structure

```
klar-mcp/
├── src/
│   ├── index.ts          # Server entry point - handles MCP protocol
│   ├── types.ts          # Shared TypeScript types
│   └── tools/
│       ├── index.ts      # Tool registry - exports all tools
│       ├── hello-world.ts    # Example: simplest possible tool
│       ├── timestamp.ts      # Example: tool with enum options
│       ├── uuid.ts           # Example: tool with optional params
│       └── ...               # More example tools
├── dist/                 # Compiled JavaScript (generated)
├── package.json
└── tsconfig.json
```

## How It Works

### 1. The Server (`src/index.ts`)

The server does three things:
1. **Creates an MCP server** with a name and version
2. **Registers handlers** for listing and calling tools
3. **Connects via stdio** so clients can communicate with it

```typescript
// Simplified version of src/index.ts
const server = new Server({ name: "klar-mcp", version: "1.0.0" }, {
  capabilities: { tools: {} }
});

// When client asks "what tools do you have?"
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: definitions  // Return all tool definitions
}));

// When client says "call this tool with these arguments"
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const handler = handlers.get(request.params.name);
  return handler(request.params.arguments);
});

// Start listening on stdin/stdout
const transport = new StdioServerTransport();
await server.connect(transport);
```

### 2. A Tool (`src/tools/hello-world.ts`)

Each tool has two parts:
- **Definition**: Name, description, and input schema (what the AI sees)
- **Handler**: The actual code that runs (what you implement)

```typescript
export const helloWorld: ToolModule = {
  definition: {
    name: "hello_world",
    description: "A simple greeting tool",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Name to greet" }
      }
    }
  },
  handler: async (args) => {
    const name = args?.name || "World";
    return {
      content: [{ type: "text", text: `Hello, ${name}!` }]
    };
  }
};
```

### 3. The Registry (`src/tools/index.ts`)

All tools are collected into two exports:
- `definitions`: Array of tool schemas (for `ListTools`)
- `handlers`: Map of name → handler function (for `CallTool`)

## Adding Your Own Tools

See [docs/ADDING-TOOLS.md](docs/ADDING-TOOLS.md) for a step-by-step guide.

**Quick version:**

1. Create `src/tools/my-tool.ts`:
```typescript
import { ToolModule } from "../types.js";

export const myTool: ToolModule = {
  definition: {
    name: "my_tool",
    description: "What this tool does",
    inputSchema: {
      type: "object",
      properties: {
        input: { type: "string", description: "The input" }
      },
      required: ["input"]
    }
  },
  handler: async (args) => {
    // Your logic here
    return {
      content: [{ type: "text", text: `Result: ${args.input}` }]
    };
  }
};
```

2. Register in `src/tools/index.ts`:
```typescript
import { myTool } from "./my-tool.js";
// ... add to tools array
```

3. Rebuild: `npm run build`

## Included Example Tools

| Tool | Description | Demonstrates |
|------|-------------|--------------|
| `hello_world` | Simple greeting | Minimal tool structure |
| `timestamp` | Get current time | Enum parameters |
| `uuid` | Generate UUIDs | Optional params with defaults |
| `base64` | Encode/decode | Required params, error handling |
| `hash` | Generate hashes | Multiple algorithms |
| `json_format` | Format/validate JSON | Complex input validation |
| `env_info` | Environment details | System interaction |
| `text_stats` | Text analysis | Object response |
| `regex_test` | Test regex patterns | Pattern matching |
| `random_string` | Generate strings | Character sets |
| `shell_command` | Run shell commands | Subprocess execution |

## Development

```bash
# Build TypeScript
npm run build

# Build and run
npm run dev

# Run tests (if you add them)
npm test
```

## Learn More

- [MCP Documentation](https://modelcontextprotocol.io/)
- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
- [MCP Specification](https://spec.modelcontextprotocol.io/)
- [Example MCP Servers](https://github.com/modelcontextprotocol/servers)

## License

MIT

Go forth and build! You have my full permission to tweak, share, edit this project as you see fit. All I ask is that if you create something cool, you share it with me. I’m always excited to see what you create. 