# MCP Reference Servers — Administrator & Developer Guide

## 1. Architecture Overview

The MCP Reference Servers repository is a monorepo containing seven independent Model Context Protocol server implementations. Each server is a standalone process that communicates with MCP clients over stdio (or HTTP, in the case of the Everything Server). The servers share no runtime state — each is deployed and configured independently.

The repository is organized as an npm workspace with TypeScript servers as direct workspace members and Python servers as independent packages with their own `pyproject.toml` build configurations.

```text
┌─────────────────────────────────────────────────┐
│                  MCP Client                      │
│  (Claude Desktop, VS Code, Cursor, etc.)        │
└──────────┬──────┬──────┬──────┬──────┬──────┬───┘
           │      │      │      │      │      │
      stdio│ stdio│ stdio│ stdio│ stdio│ stdio│
           │      │      │      │      │      │
     ┌─────▼──┐ ┌─▼────┐ ┌▼────┐ ┌▼───┐ ┌▼──┐ ┌▼──────────────┐
     │Filesys.│ │Memory│ │Seq. │ │Git │ │Fetch│ │Time│Everything│
     │Server  │ │Server│ │Think│ │Srv │ │Srv  │ │Srv │  Server  │
     │(TS)    │ │(TS)  │ │(TS) │ │(Py)│ │(Py) │ │(Py)│  (TS)   │
     └────────┘ └──────┘ └─────┘ └────┘ └─────┘ └────┴──────────┘
```

### Component Inventory

| Component | Path | Language | npm/PyPI Package | Version |
|---|---|---|---|---|
| Filesystem Server | `src/filesystem/` | TypeScript | `@modelcontextprotocol/server-filesystem` | 0.6.3 |
| Memory Server | `src/memory/` | TypeScript | `@modelcontextprotocol/server-memory` | 0.6.3 |
| Sequential Thinking Server | `src/sequentialthinking/` | TypeScript | `@modelcontextprotocol/server-sequential-thinking` | 0.6.2 |
| Everything Server | `src/everything/` | TypeScript | `@modelcontextprotocol/server-everything` | 2.0.0 |
| Fetch Server | `src/fetch/` | Python | `mcp-server-fetch` | — |
| Git Server | `src/git/` | Python | `mcp-server-git` | — |
| Time Server | `src/time/` | Python | `mcp-server-time` | — |

### Technology Stack

| Layer | Technology |
|---|---|
| MCP SDK (TypeScript) | `@modelcontextprotocol/sdk` ^1.26.0 |
| MCP SDK (Python) | `mcp` (PyPI) |
| TypeScript build | `tsc` (TypeScript 5.6+) |
| Schema validation | `zod` (TS), `pydantic` (Python) |
| Testing | Vitest (TS), pytest (Python) |
| HTTP framework (Everything Server only) | Express 5.x with CORS |
| Git operations | GitPython (`git` PyPI package) |
| HTML extraction | `readabilipy`, `markdownify` |
| Timezone handling | `zoneinfo` (stdlib), `tzlocal` |

> [!NOTE]
> The root `package.json` declares `"type": "module"` and uses npm workspaces. The four TypeScript servers are workspace members under `src/*`. Python servers are independent — they have their own `pyproject.toml` and are not part of the npm workspace build.

## 2. System Requirements

| Requirement | Minimum | Recommended |
|---|---|---|
| Node.js | 18.x | 22.x LTS |
| Python | 3.10 | 3.12+ |
| npm | 9.x | 10.x |
| Git (for git server) | 2.30+ | Latest |
| OS | Linux, macOS, Windows | Any |
| Memory | 128 MB per server | 256 MB |
| Disk | Minimal (servers are stateless except Memory) | — |

### Build Requirements (from source)

```bash
git clone https://github.com/modelcontextprotocol/servers.git
cd servers
npm install          # Installs all workspace dependencies
npm run build        # Builds all TypeScript servers
```

For Python servers:

```bash
cd src/fetch && uv sync
cd src/git && uv sync
cd src/time && uv sync
```

## 3. Configuration Reference

### Environment Variables

| Variable | Server | Type | Default | Description | Required |
|---|---|---|---|---|---|
| `MEMORY_FILE_PATH` | Memory | string | `memory.jsonl` (co-located with dist) | Absolute or relative path to the JSONL knowledge graph file | No |
| `DISABLE_THOUGHT_LOGGING` | Sequential Thinking | boolean string | `"false"` | Set to `"true"` to suppress thought output to stderr | No |

> [!IMPORTANT]
> The Memory Server auto-migrates legacy `memory.json` files to `memory.jsonl` on startup. If both files exist, the JSONL version is used. The migration is logged to stderr.

### Server Arguments

#### Filesystem Server

```text
mcp-server-filesystem [directory1] [directory2] ...
```

- Zero or more allowed directory paths as positional arguments
- Supports `~` home directory expansion
- Resolves symlinks at startup for security (both original and resolved paths are tracked)
- If no directories are provided, the server starts in a waiting state and expects MCP roots from the client

#### Git Server

```text
mcp-server-git [--repository PATH]
```

- `--repository`: Optional. Restricts all operations to a single repository path
- Without `--repository`, the server accepts `repo_path` in each tool call and validates it
- Supports MCP roots protocol for repository discovery

#### Fetch Server

```text
mcp-server-fetch [--custom-user-agent AGENT] [--ignore-robots-txt] [--proxy-url URL]
```

| Flag | Type | Default | Description |
|---|---|---|---|
| `--custom-user-agent` | string | `ModelContextProtocol/1.0 (Autonomous; ...)` | Custom User-Agent for all requests |
| `--ignore-robots-txt` | flag | `false` | Skip robots.txt compliance checks |
| `--proxy-url` | string | None | HTTP proxy URL for all requests |

#### Time Server

```text
mcp-server-time [--local-timezone TIMEZONE]
```

- `--local-timezone`: Override automatic local timezone detection with an IANA timezone name
- Falls back to system timezone detection via `tzlocal`, then UTC if detection fails

#### Everything Server

```text
mcp-server-everything [stdio|sse|streamableHttp]
```

- First positional argument selects the transport mode (default: `stdio`)
- `sse` and `streamableHttp` modes start an Express HTTP server (used for testing HTTP-based MCP transports)

### MCP Capabilities Declared

| Server | Tools | Prompts | Resources | Logging | Tasks | Roots |
|---|---|---|---|---|---|---|
| Filesystem | Yes | — | — | — | — | Yes (listens for `roots/list_changed`) |
| Memory | Yes | — | — | — | — | — |
| Sequential Thinking | Yes | — | — | — | — | — |
| Everything | Yes (listChanged) | Yes (listChanged) | Yes (subscribe, listChanged) | Yes | Yes (list, cancel) | Yes |
| Fetch | Yes | Yes | — | — | — | — |
| Git | Yes | — | — | — | — | Yes (reads roots) |
| Time | Yes | — | — | — | — | — |

## 4. Deployment & Scaling

### Docker Deployment

Each server includes a `Dockerfile` in its source directory. Build and run examples:

```bash
# Filesystem server
docker build -t mcp-filesystem src/filesystem/
docker run -v /host/data:/data mcp-filesystem /data

# Fetch server
docker build -t mcp-fetch src/fetch/
docker run mcp-fetch
```

> [!TIP]
> When running filesystem-aware servers in Docker, mount directories as volumes and pass the container-side paths as allowed directories. The paths inside the container must match the arguments.

### Scaling Considerations

MCP servers are inherently single-session. Each MCP client connection spawns a new server process. There is no built-in connection pooling or multi-tenancy.

- **Horizontal scaling**: Spawn one server process per client session (this is the default behavior)
- **Resource isolation**: Each server process has its own memory space
- **Memory Server concurrency**: The JSONL file has no locking — concurrent writes from multiple server instances to the same file will cause corruption. Use separate files per client or implement external locking

> [!WARNING]
> The Memory Server's JSONL storage does not support concurrent access. If multiple server instances share the same `MEMORY_FILE_PATH`, data corruption will occur. Each client session should use its own file path.

### Everything Server HTTP Modes

The Everything Server supports three transport modes for testing MCP client implementations:

**SSE mode** (`node dist/index.js sse`):
- Starts an Express server with CORS enabled
- Creates a new MCP server instance per SSE connection
- Suitable for browser-based MCP clients

**Streamable HTTP mode** (`node dist/index.js streamableHttp`):
- Uses the newer bidirectional HTTP streaming transport
- Session-based with stateful server instances keyed by session ID
- Handles `GET` (SSE stream), `POST` (messages), and `DELETE` (session cleanup)

## 5. Operations

### Health Monitoring

MCP servers do not expose health endpoints (except the Everything Server in HTTP mode). Monitor server health by:

1. **Process monitoring**: Check that the server process is running
2. **stderr logging**: All servers log startup messages and errors to stderr
3. **MCP client status**: Most MCP clients show server connection status in their UI

### Filesystem Server — Startup Validation

The filesystem server performs validation at startup:

1. Expands `~` in directory paths
2. Resolves all paths to absolute form
3. Resolves symlinks (stores both original and resolved paths)
4. Filters out inaccessible or non-directory paths (with stderr warnings)
5. Exits with code 1 only if ALL specified directories are inaccessible

```text
Warning: Cannot access directory /nonexistent, skipping
Warning: /tmp/file.txt is not a directory, skipping
Secure MCP Filesystem Server running on stdio
```

### Filesystem Server — Dynamic Roots Updates

When the MCP client supports the roots protocol:

1. On initialization, the server requests roots from the client
2. If roots are received, they **replace** all CLI-configured allowed directories
3. The server listens for `roots/list_changed` notifications and updates dynamically
4. If the client provides empty roots, the server retains its current configuration

> [!NOTE]
> This means CLI-configured directories are effectively defaults that get overridden when a roots-capable client connects. This is intentional — the roots protocol gives the client control over the security boundary.

### Memory Server — Data Management

**File format** (JSONL):

```jsonl
{"type":"entity","name":"Alice","entityType":"Person","observations":["Works at Acme Corp"]}
{"type":"entity","name":"Acme Corp","entityType":"Organization","observations":["Founded 2020"]}
{"type":"relation","from":"Alice","to":"Acme Corp","relationType":"works_at"}
```

**Backup**: Copy the JSONL file. It's a plain text file with one JSON object per line.

**Migration**: The server automatically detects `memory.json` (legacy format) and renames it to `memory.jsonl` on startup.

> [!TIP]
> To inspect the knowledge graph without an MCP client, read the JSONL file directly: `cat memory.jsonl | python -m json.tool --json-lines`

### Log Output

All servers log to stderr (never stdout — stdout is reserved for MCP protocol messages).

| Server | Startup Message |
|---|---|
| Filesystem | `Secure MCP Filesystem Server running on stdio` |
| Memory | `Knowledge Graph MCP Server running on stdio` |
| Sequential Thinking | `Sequential Thinking MCP Server running on stdio` |
| Everything | (varies by transport mode) |
| Fetch | (inherits from MCP SDK) |
| Git | (inherits from MCP SDK) |
| Time | (inherits from MCP SDK) |

## 6. Performance

### Filesystem Server

- **File reading**: Streams large files via `createReadStream` for media files (base64 encoding)
- **Tail operation**: Memory-efficient chunked reading from file end (1KB chunks) — does not read entire file into memory
- **Head operation**: Chunked reading from file start with early termination
- **Directory tree**: Recursive traversal with glob-based exclude patterns via `minimatch`
- **File editing**: Atomic writes using temporary files and `fs.rename()` — prevents partial writes on crash

### Memory Server

- **Load**: Reads entire JSONL file on every operation (no caching)
- **Save**: Rewrites entire file on every mutation
- **Search**: Linear scan of all entities and observations (O(n) where n = total observation count)
- **Deduplication**: Entities are deduplicated by `name`, relations by `(from, to, relationType)` tuple

> [!NOTE]
> The Memory Server is designed for moderate-sized knowledge graphs (hundreds to low thousands of entities). For larger datasets, the full-file read/write pattern becomes a bottleneck.

### Sequential Thinking Server

- **State**: In-memory only — thought history and branches are lost when the server process exits
- **Processing**: Synchronous, single-threaded — each thought is processed immediately

## 7. Security

### Filesystem Server — Path Sandboxing

The filesystem server implements defense-in-depth path validation:

1. **Startup normalization**: All allowed directories are resolved to absolute paths with symlinks resolved
2. **Request validation** (`validatePath`):
   - Expands `~` home directory notation
   - Resolves relative paths against allowed directories
   - Checks the normalized path is within an allowed directory
   - Resolves symlinks on the target path to prevent symlink traversal
   - For new files, validates the parent directory
3. **Atomic writes**: Uses temporary files + `fs.rename()` to prevent TOCTOU (time-of-check-time-of-use) race conditions
4. **Exclusive creation**: New files use `wx` flag (fails if file/symlink already exists), falling back to atomic rename for overwrites
5. **Path traversal prevention**: `isPathWithinAllowedDirectories()` rejects null bytes, normalizes both paths, and uses `path.sep`-aware prefix checking (not naive string matching)

> [!CAUTION]
> The symlink resolution at both startup and request time is critical. Without it, an attacker could create a symlink inside an allowed directory pointing to `/etc/passwd` and read it through the server.

### Filesystem Server — Platform-Specific Path Handling

The `path-utils.ts` module handles cross-platform path normalization:

- **macOS**: Resolves `/tmp` → `/private/tmp` symlink by storing both paths
- **Windows**: Handles drive letter capitalization, UNC paths, `/c/` → `C:\` conversion
- **WSL**: Preserves `/mnt/c/` paths without converting them (they're valid Linux paths)
- **Relative paths**: Resolved against the first allowed directory

### Git Server — Input Validation

All Git server functions implement defense-in-depth against flag injection:

- Branch names, revision identifiers, timestamps, and `contains`/`not_contains` values are rejected if they start with `-`
- `git_add` uses `--` separator to prevent filenames starting with `-` from being interpreted as options
- `git_diff` validates the target is a real Git ref via `repo.rev_parse()` before execution
- `repo_path` is validated against the optional `--repository` restriction using resolved path comparison

### Fetch Server — Robots.txt Compliance

The fetch server uses the `protego` library to parse `robots.txt`:

1. Before autonomous fetching, retrieves the site's `robots.txt`
2. Strips comments and parses with Protego
3. Checks if the User-Agent is allowed to fetch the target URL
4. Returns a descriptive error if blocked, suggesting the user try the manual `fetch` prompt
5. Treats HTTP 401/403 on `robots.txt` as "autonomous fetching not allowed"
6. Treats HTTP 4xx (non-401/403) on `robots.txt` as "no restrictions"

> [!WARNING]
> The `--ignore-robots-txt` flag bypasses all compliance checks. This should only be used for sites you own or have explicit permission to scrape.

### Everything Server — Experimental Features

The Everything Server uses experimental MCP SDK features including:

- `InMemoryTaskStore` and `InMemoryTaskMessageQueue` for task management
- Sampling request tools that ask the client to perform LLM inference
- Elicitation request tools that ask the client to gather user input

These are protocol demonstration features, not production security surfaces.

## 8. Developer Internals

### Repository Structure

```text
modelcontextprotocol/servers/
├── package.json              # Root workspace config (v0.6.2)
├── tsconfig.json             # Shared TypeScript config
├── .npmrc                    # npm configuration
├── scripts/
│   └── release.py            # Multi-package release script
├── src/
│   ├── filesystem/           # Filesystem MCP server (TypeScript)
│   │   ├── index.ts          # Entry point, tool registrations
│   │   ├── lib.ts            # Core file operations, path validation
│   │   ├── path-utils.ts     # Cross-platform path normalization
│   │   ├── path-validation.ts # isPathWithinAllowedDirectories()
│   │   ├── roots-utils.ts    # MCP roots → directory resolution
│   │   └── __tests__/        # Vitest test suite
│   ├── memory/               # Memory (knowledge graph) server (TypeScript)
│   │   ├── index.ts          # Entry point, KnowledgeGraphManager, tool registrations
│   │   └── __tests__/        # Tests
│   ├── sequentialthinking/   # Sequential Thinking server (TypeScript)
│   │   ├── index.ts          # Entry point, tool registration
│   │   ├── lib.ts            # SequentialThinkingServer class
│   │   └── __tests__/        # Tests
│   ├── everything/           # Everything (reference) server (TypeScript)
│   │   ├── index.ts          # Transport launcher (stdio/sse/streamableHttp)
│   │   ├── server/           # Server factory, logging, roots
│   │   ├── tools/            # 18 tool implementations
│   │   ├── prompts/          # 4 prompt implementations
│   │   ├── resources/        # Resource templates, subscriptions
│   │   ├── transports/       # stdio, SSE, streamableHttp adapters
│   │   ├── docs/             # Server instructions (bundled)
│   │   └── __tests__/        # Tests
│   ├── fetch/                # Fetch server (Python)
│   │   ├── pyproject.toml    # Package config
│   │   └── src/mcp_server_fetch/
│   │       ├── __init__.py   # main() entry point
│   │       ├── __main__.py   # python -m support
│   │       └── server.py     # Fetch tool/prompt implementation
│   ├── git/                  # Git server (Python)
│   │   ├── pyproject.toml    # Package config
│   │   └── src/mcp_server_git/
│   │       ├── __init__.py   # main() entry point
│   │       ├── __main__.py   # python -m support
│   │       └── server.py     # 12 git tools implementation
│   └── time/                 # Time server (Python)
│       ├── pyproject.toml    # Package config
│       └── src/mcp_server_time/
│           ├── __init__.py   # main() entry point
│           ├── __main__.py   # python -m support
│           └── server.py     # TimeServer class, 2 tools
```

### Module Reference

#### `src/filesystem/index.ts` — Filesystem Server Entry Point

Main entry point and tool registration module. Parses command-line arguments for allowed directories, initializes path normalization and symlink resolution, registers all 14 filesystem tools, sets up MCP roots protocol handlers, and starts the stdio transport.

Key behaviors:
- Registers both deprecated `read_file` and replacement `read_text_file` (same handler)
- Tool annotations mark destructive tools (`write_file`, `edit_file`, `move_file`) and read-only tools
- On initialization, fetches roots from the client if supported, replacing CLI directories
- Listens for `roots/list_changed` notifications for dynamic directory updates

#### `src/filesystem/lib.ts` — Core File Operations

Contains all path validation logic and file operation implementations:

- `validatePath()` — security-critical path validation with symlink resolution
- `applyFileEdits()` — find-and-replace with whitespace-flexible matching and atomic writes
- `tailFile()` / `headFile()` — memory-efficient partial file reading
- `searchFilesWithValidation()` — recursive glob search with path validation
- `writeFileContent()` — atomic write using exclusive creation + rename fallback
- `createUnifiedDiff()` — git-style diff generation using the `diff` library

#### `src/filesystem/path-utils.ts` — Cross-Platform Path Normalization

Handles Windows, macOS, Linux, and WSL path formats:

- `normalizePath()` — strips quotes, normalizes separators, capitalizes drive letters, handles UNC paths
- `convertToWindowsPath()` — converts `/c/...` to `C:\...` on Windows (preserves WSL `/mnt/` paths)
- `expandHome()` — resolves `~/` to the user's home directory

#### `src/filesystem/path-validation.ts` — Directory Boundary Enforcement

- `isPathWithinAllowedDirectories()` — pure function that checks if a normalized absolute path falls within any allowed directory, handling null bytes, drive roots, UNC paths, and platform-specific separators

#### `src/filesystem/roots-utils.ts` — MCP Roots Resolution

- `getValidRootDirectories()` — converts MCP Root specifications (file URIs or plain paths) to validated directory paths with symlink resolution
- `parseRootUri()` — handles `file://` URIs, home directory expansion, and path resolution

#### `src/memory/index.ts` — Memory Server

Single-file server containing:

- `KnowledgeGraphManager` class — CRUD operations on entities, relations, and observations
- JSONL file I/O with automatic legacy `memory.json` migration
- 9 registered tools for graph manipulation and querying
- `searchNodes()` — case-insensitive substring search across names, types, and observations
- `openNodes()` — exact-name entity lookup with inclusive relation filtering

#### `src/sequentialthinking/lib.ts` — Sequential Thinking Engine

- `SequentialThinkingServer` class — processes thoughts with branching, revision, and dynamic total adjustment
- `formatThought()` — chalk-colored stderr output with box-drawing characters
- Maintains `thoughtHistory` array and `branches` record for the session lifetime

#### `src/everything/server/index.ts` — Everything Server Factory

- `createServer()` — factory function returning `{server, cleanup}`
- Configures all MCP capabilities: tools (listChanged), prompts (listChanged), resources (subscribe, listChanged), logging, tasks (list, cancel, requests)
- Registers tools in two phases: unconditional tools at creation, conditional tools after initialization (when client capabilities are known)
- Cleanup function stops simulated logging/resource intervals and clears task store timers

#### `src/everything/tools/index.ts` — Everything Server Tools

Registers 18 tools in two groups:

**Unconditional tools** (12, registered at server creation):
`echo`, `get-annotated-message`, `get-env`, `get-resource-links`, `get-resource-reference`, `get-structured-content`, `get-sum`, `get-tiny-image`, `gzip-file-as-resource`, `toggle-simulated-logging`, `toggle-subscriber-updates`, `trigger-long-running-operation`

**Conditional tools** (6, registered after initialization):
`get-roots-list`, `trigger-elicitation-request`, `trigger-sampling-request`, `simulate-research-query`, `trigger-sampling-request-async`, `trigger-elicitation-request-async`

#### `src/everything/prompts/` — Everything Server Prompts

Four prompt implementations demonstrating different MCP prompt patterns:

| Prompt | File | Pattern Demonstrated |
|---|---|---|
| `simple-prompt` | `simple.ts` | No arguments, fixed text |
| `args-prompt` | `args.ts` | Required + optional string arguments |
| `completable-prompt` | `completions.ts` | Arguments with completion handlers (context-dependent) |
| `resource-prompt` | `resource.ts` | Embedded resource reference in prompt response |

#### `src/fetch/src/mcp_server_fetch/server.py` — Fetch Server

- `fetch_url()` — HTTP GET with `httpx.AsyncClient`, HTML-to-Markdown conversion via `readabilipy` + `markdownify`
- `check_may_autonomously_fetch_url()` — robots.txt compliance using `protego`
- Dual User-Agent strategy: autonomous (tool) vs. user-specified (prompt)
- Content truncation with pagination support (`start_index`, `max_length`)

#### `src/git/src/mcp_server_git/server.py` — Git Server

- 12 Git tool functions wrapping `GitPython` operations
- `validate_repo_path()` — restricts operations to the configured repository path
- `list_repos()` — discovers repositories from CLI args and MCP roots
- Flag injection prevention on all user-supplied ref names and timestamps
- `git_log()` supports date-filtered queries via `--since`/`--until`

#### `src/time/src/mcp_server_time/server.py` — Time Server

- `TimeServer` class with `get_current_time()` and `convert_time()` methods
- Uses `zoneinfo.ZoneInfo` for timezone resolution
- `get_local_tz()` — falls back through: override arg → `tzlocal` detection → UTC
- Handles fractional UTC offsets (e.g., Nepal's UTC+5:45)
- Returns structured `TimeResult` / `TimeConversionResult` Pydantic models

### Code Patterns and Conventions

**Tool registration pattern (TypeScript):**

All TypeScript servers use the `McpServer.registerTool()` API from `@modelcontextprotocol/sdk`:

```typescript
server.registerTool(
  "tool_name",
  {
    title: "Human-Readable Title",
    description: "Tool description for the AI assistant",
    inputSchema: { /* Zod schema */ },
    outputSchema: { /* Zod schema */ },
    annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
  },
  async (args) => {
    // Implementation
    return {
      content: [{ type: "text", text: result }],
      structuredContent: { /* typed result */ }
    };
  }
);
```

**Tool registration pattern (Python):**

Python servers use the lower-level `Server` API with decorators:

```python
server = Server("server-name")

@server.list_tools()
async def list_tools() -> list[Tool]:
    return [Tool(name="tool_name", description="...", inputSchema=Model.model_json_schema())]

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    match name:
        case "tool_name":
            return [TextContent(type="text", text=result)]
```

**Error handling:**

- TypeScript servers throw standard `Error` objects — the MCP SDK converts them to protocol error responses
- Python servers raise `McpError` with `ErrorData` for protocol-level errors, or `ValueError` for validation errors
- The Git server uses `BadName` from `git.exc` for invalid ref names

**Structured content:**

All TypeScript servers return both `content` (text array for backward compatibility) and `structuredContent` (typed object matching the `outputSchema`). This enables clients to consume tool results programmatically.

### Testing Strategy

All servers use Vitest (TypeScript) or pytest (Python) with the following structure:

| Server | Test Directory | Test Count | Coverage |
|---|---|---|---|
| Filesystem | `src/filesystem/__tests__/` | 7 test files | Path validation, directory tree, startup validation |
| Memory | `src/memory/__tests__/` | 2 test files | Knowledge graph CRUD, file path handling |
| Sequential Thinking | `src/sequentialthinking/__tests__/` | 1 test file | Thought processing |
| Everything | `src/everything/__tests__/` | 5 test files | Server factory, tools, prompts, resources, registrations |
| Fetch | `src/fetch/tests/` | 1 test file | Server functionality |
| Git | `src/git/tests/` | 1 test file | Git operations |
| Time | `src/time/test/` | 1 test file | Time operations |

Run all TypeScript tests:

```bash
npm test --workspaces
```

Run a specific server's tests:

```bash
cd src/filesystem && npx vitest run --coverage
```

Run Python tests:

```bash
cd src/fetch && uv run pytest
cd src/git && uv run pytest
cd src/time && uv run pytest
```

### Build System

**TypeScript build** (`npm run build`):

1. Runs `tsc` in each workspace to compile TypeScript to JavaScript in `dist/`
2. The Everything Server additionally copies `docs/` into `dist/` (server instructions are bundled)
3. `shx chmod +x dist/*.js` makes entry points executable (Unix)
4. `prepare` scripts ensure builds run before `npm publish`

**Release process** (`scripts/release.py`):

A Python script that handles multi-package versioning and npm publishing for the workspace.

> [!NOTE]
> GitHub Issue #3870 reports that the release script skips version bumps for packages that only have lockfile changes. This can cause stale versions on npm.

### Potential Improvements

Based on code analysis and open issues:

1. **Memory Server persistence**: Replace full-file read/write with append-only operations and periodic compaction for better performance at scale
2. **Memory Server concurrency**: Add file locking (e.g., `proper-lockfile`) to support multiple concurrent server instances safely
3. **Git Server remote operations**: Add `git_push`, `git_pull`, `git_fetch` for complete workflow support (currently local-only)
4. **Filesystem Server structured output**: Several tools already return `structuredContent` — ensure all tools have typed output schemas
5. **Test coverage**: Python servers have minimal test coverage (1 file each) compared to TypeScript servers

### Contributing

The repository follows standard open-source contribution practices:

1. Fork and clone the repository
2. Create a feature branch
3. Run existing tests: `npm test --workspaces`
4. Add tests for new functionality
5. Ensure TypeScript builds cleanly: `npm run build`
6. Submit a pull request

The project uses Prettier for code formatting (Everything Server has its own `.prettierignore`). Run `npm run prettier:check` in the Everything Server directory to verify formatting.

## 9. Integration Points

### MCP Roots Protocol

The Filesystem and Git servers integrate with the MCP roots protocol for dynamic directory/repository discovery:

**Filesystem Server:**
- Requests roots on initialization
- Replaces CLI-configured directories with client-provided roots
- Listens for `roots/list_changed` notifications and updates allowed directories dynamically
- Uses `roots-utils.ts` to validate root URIs (supports `file://` and plain paths)

**Git Server:**
- Discovers repositories from roots via `list_repos()`
- Combines root-based and CLI-based repository lists
- Validates `repo_path` against the `--repository` restriction for security

**Everything Server:**
- Demonstrates roots protocol integration
- Tracks roots per session in a `Map<sessionId, Root[]>`
- Registers `roots/list_changed` notification handler

### MCP SDK Integration

All servers depend on `@modelcontextprotocol/sdk` (TypeScript) or `mcp` (Python):

**TypeScript servers use:**
- `McpServer` — high-level server class with `registerTool()`, `registerPrompt()`, `registerResource()`
- `StdioServerTransport` — stdio communication layer
- `zod` schemas for input/output validation (integrated with the SDK)

**Python servers use:**
- `Server` — lower-level server with decorator-based tool/prompt registration
- `stdio_server()` — async context manager for stdio communication
- `pydantic` models for input schema generation via `model_json_schema()`

### Structured Content

TypeScript servers return both legacy `content` (text array) and `structuredContent` (typed object) from tool calls. This allows MCP clients to:

1. Display formatted text (via `content`)
2. Programmatically consume typed results (via `structuredContent`)
3. Validate outputs against the `outputSchema` declared in tool registration

---

_Generated May 2026 from modelcontextprotocol/servers at 4503e2d. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
