# MCP Tool Finder Server

Progressive disclosure tool discovery for MCP code execution pattern.

## Overview

This MCP server implements the `search_tools` pattern described in [Anthropic's blog post on Code Execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp).

Instead of loading all 50,000 tokens of tool definitions upfront, agents can progressively discover and load only the tools they need:

1. **Search** with name-only (~10 tokens per tool)
2. **Browse** with descriptions (~50 tokens per tool)
3. **Load** full definitions only when ready to use (~200 tokens per tool)

This maintains the **98.6% token savings** of the code execution with MCP pattern.

## Tool: `search_tools`

### Purpose

Search through available MCP tool wrappers in the mcp-executor system and return filtered results with configurable detail levels.

### Parameters

```python
query: str                    # Search term (required)
detail_level: str            # "name-only" | "name-and-description" | "full-definition"
server: Optional[str]        # Filter by server name (optional)
```

### Detail Levels

#### `name-only` (Default)
Returns just tool names - most token-efficient for initial discovery.

```json
{
  "format": "name-only",
  "count": 3,
  "tools": ["writeNote", "readNote", "deleteNote"]
}
```
**Token usage**: ~10 tokens per tool

#### `name-and-description`
Returns names with brief descriptions - helpful for understanding what tools do.

```json
{
  "format": "name-and-description",
  "count": 2,
  "tools": [
    {
      "name": "writeNote",
      "server": "basic-memory",
      "description": "Create or update a markdown note"
    },
    {
      "name": "readNote",
      "server": "basic-memory",
      "description": "Read note contents"
    }
  ]
}
```
**Token usage**: ~50 tokens per tool

#### `full-definition`
Returns complete TypeScript interfaces with all parameters - use when ready to implement.

```json
{
  "format": "full-definition",
  "count": 1,
  "tools": [
    {
      "name": "writeNote",
      "server": "basic-memory",
      "description": "Create or update a markdown note",
      "file_path": "src/servers/basic-memory/writeNote.ts",
      "interface": "export interface WriteNoteInput { ... }",
      "parameters": {
        "title": {"type": "string", "required": true},
        "content": {"type": "string", "required": true},
        "folder": {"type": "string", "required": true},
        "project": {"type": "string", "required": false}
      }
    }
  ]
}
```
**Token usage**: ~200 tokens per tool

### Usage Examples

#### Example 1: Find tools related to writing
```python
search_tools(
    query="write",
    detail_level="name-only"
)
# Returns: ["writeNote", "editNote"]
```

#### Example 2: Get descriptions for basic-memory server
```python
search_tools(
    query="basic-memory",
    detail_level="name-and-description"
)
# Returns: All basic-memory tools with descriptions
```

#### Example 3: Get full definition for specific tool
```python
search_tools(
    query="writeNote",
    detail_level="full-definition"
)
# Returns: Complete TypeScript interface with parameters
```

#### Example 4: Filter by server
```python
search_tools(
    query="note",
    server="basic-memory",
    detail_level="name-and-description"
)
# Returns: Only basic-memory tools matching "note"
```

## Installation

1. Install dependencies:
```bash
pip install -r requirements.txt
```

2. Add to `.mcp.json`:
```json
{
  "mcpServers": {
    "tool-finder": {
      "command": "python",
      "args": [
        "/absolute/path/to/backend/mcp-executor/servers/tool-finder/server.py"
      ]
    }
  }
}
```

## Progressive Disclosure Workflow

### Traditional Approach (❌ 50,000 tokens)
```
Load all tool definitions upfront → Process entire schema → Use what you need
```

### Progressive Disclosure (✅ 500 tokens)
```
1. search_tools(query="write", detail_level="name-only")
   → See: ["writeNote", "editNote", "deleteNote"] (~30 tokens)

2. search_tools(query="writeNote", detail_level="name-and-description")
   → Get description to confirm it's the right tool (~50 tokens)

3. search_tools(query="writeNote", detail_level="full-definition")
   → Load complete interface when ready to use (~200 tokens)

Total: ~280 tokens instead of 50,000 tokens = 99.4% savings!
```

## Error Handling

### No Results Found
```json
{
  "count": 0,
  "tools": [],
  "message": "No tools found matching query 'xyz'",
  "suggestion": "Try broader search terms like 'write', 'search', or server names",
  "available_servers": ["basic-memory", "time", "linear-server"]
}
```

### Response Too Large
```json
{
  "truncated": true,
  "message": "Response truncated to 25,000 characters. Use more specific query or lower detail_level.",
  "count": 15,
  "tools": [ ... first 15 tools that fit in limit ... ]
}
```

## Architecture

### File Scanning
- Recursively scans `../../src/servers/` directory
- Finds all `.ts` files (excludes tests, type definitions, index files)
- Parses each file to extract tool metadata

### TypeScript Parsing
Extracts from each tool wrapper:
- **Function name**: From `export async function functionName(`
- **Description**: From JSDoc comments or inline comments
- **Interface**: Full TypeScript interface definition
- **Parameters**: Parsed parameter names, types, and required status

### Search Algorithm
Performs case-insensitive substring matching on:
- Tool name
- Server name
- Description text

### Response Formatting
- **name-only**: Simple string array
- **name-and-description**: Objects with name, server, description
- **full-definition**: Complete tool metadata including interfaces

### Truncation Strategy
- Character limit: 25,000 characters
- Truncates tool list to fit within limit
- Adds truncation warning and suggestion

## Token Savings Calculation

### Example: 10 MCP servers with 50 tools total

**Traditional Approach:**
- Load all 50 tool definitions: 50,000 tokens
- Intermediate results flow through context
- Total: ~75,000 tokens

**Progressive Disclosure:**
- Initial search (name-only): 50 tools × 10 tokens = 500 tokens
- Drill down (descriptions): 5 tools × 50 tokens = 250 tokens
- Load full definition: 2 tools × 200 tokens = 400 tokens
- Total: ~1,150 tokens

**Savings: 98.5%** 🎉

## Security

- **Path Validation**: Only scans predefined directories
- **No Code Execution**: Parses text only, doesn't execute TypeScript
- **Character Limits**: Prevents massive responses
- **Error Messages**: Don't expose sensitive system paths

## Compatibility

- **Python**: 3.8+
- **FastMCP**: 2.0.0+
- **Pydantic**: 2.0.0+

## Related Documentation

- [Anthropic Blog: Code Execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp)
- [MCP Executor TOOLS.md](../../TOOLS.md) - Complete tool parameter reference
- [Model Context Protocol](https://modelcontextprotocol.io/)
