lazy-mcp 2.2.4

MCP proxy that lazy-loads servers and exposes them as four meta-tools
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# Lazy MCP Proxy

![Pipeline Status](https://gitlab.com/gitlab-org/ai/lazy-mcp/badges/main/pipeline.svg)

A proxy tool that converts normal MCP servers to use a lazy-loading pattern, dramatically reducing initial context usage by 90%+ and enabling support for hundreds of commands.

## Table of Contents

<!-- TOC_START -->
  - [Table of Contents]#table-of-contents
  - [Features]#features
  - [How It Works]#how-it-works
  - [Installation]#installation
  - [Usage]#usage
  - [Claude Desktop / OpenCode Integration]#claude-desktop--opencode-integration
  - [Example]#example
  - [Development]#development
  - [Releases]#releases
    - [How It Works]#how-it-works
    - [Required CI/CD Variables]#required-cicd-variables
      - [`GITLAB_RELEASE_TOKEN`]#gitlabreleasetoken
      - [`NPM_TOKEN`]#npmtoken
      - [`PYPI_TOKEN`]#pypitoken
      - [`CARGO_TOKEN`]#cargotoken
  - [Configuration Reference]#configuration-reference
    - [Server Configuration Fields]#server-configuration-fields
    - [OAuth 2.0 Authentication]#oauth-20-authentication
    - [Command Format]#command-format
    - [Environment Variables]#environment-variables
    - [Health Monitoring]#health-monitoring
    - [Config Reload (SIGHUP)]#config-reload-sighup
  - [Benefits]#benefits
  - [Documentation]#documentation
<!-- TOC_END -->

## Features

- **Multi-Server Aggregation**: Aggregate multiple MCP servers with on-demand discovery
- **Lazy Loading**: Only discover tools when needed, not upfront
- **Batch Discovery**: Discover multiple servers in one call
- **90%+ Context Reduction**: From ~16K to ~1.5K tokens initially
- **Built-in OAuth 2.0 + PKCE**: Authenticate with OAuth-protected remote servers without a browser — works in sandboxed agent environments
- **Background Health Monitoring**: Probes all servers on startup and periodically; `list_servers` shows accurate health from the first call
- **Hot Config Reload**: Send `SIGHUP` to reload config without restarting — add, remove, or update servers on the fly

## How It Works

Aggregates multiple MCP servers and exposes four meta-tools:

- `list_servers` - Lists all configured MCP servers with health status. Response includes `pid` and `config_file` so an agent can fix broken config and reload via `kill -HUP <pid>`
- `list_commands` - Discovers tools from specific server(s), supports batch discovery
- `describe_commands` - Gets detailed schemas from a server
- `invoke_command` - Executes commands from a specific server

## Installation

**Homebrew** (macOS and Linux, no runtime dependencies):

```bash
brew tap gitlab-org/lazy-mcp https://gitlab.com/gitlab-org/ai/lazy-mcp
brew install lazy-mcp
```

**Cargo** (if you have Rust installed, no Node.js required):

```bash
cargo install lazy-mcp
```

**If you have Python / uv** (no Node.js required):

```bash
uvx lazy-mcp
```

**If you have Node.js** — use npx to always get the latest version:

```bash
npx lazy-mcp@latest
```

Or install globally (locks to specific version):

```bash
npm install -g lazy-mcp
```

## Usage

Create a configuration file at `~/.config/lazy-mcp/servers.json`:

```json
{
  "servers": [
    {
      "name": "chrome-devtools",
      "description": "Chrome DevTools automation",
      "command": ["npx", "-y", "chrome-devtools-mcp@latest"]
    },
    {
      "name": "gitlab",
      "description": "GitLab MCP server",
      "url": "https://gitlab.com/api/v4/mcp"
    },
    {
      "name": "my-remote-server",
      "description": "Custom remote MCP server with static token",
      "url": "https://api.example.com/mcp",
      "headers": {
        "Authorization": "Bearer ${API_TOKEN}"
      }
    },
    {
      "name": "glean",
      "description": "Glean enterprise search (OAuth)",
      "url": "https://your-company.glean.com/mcp/default"
    }
  ]
}
```

Then run:

```bash
# Using npx (recommended - always latest version)
npx lazy-mcp@latest --config ~/.config/lazy-mcp/servers.json

# Or via environment variable
LAZY_MCP_CONFIG=~/.config/lazy-mcp/servers.json npx lazy-mcp@latest

# Or if installed globally
lazy-mcp --config ~/.config/lazy-mcp/servers.json
```

## Claude Desktop / OpenCode Integration

Replace multiple MCP server entries with one aggregated proxy:

**Before** (5 separate MCP servers):
```json
{
  "mcp": {
    "chrome-devtools": { "command": ["npx", "lazy-mcp@latest", "npx", "-y", "chrome-devtools-mcp@latest"] },
    "gitlab": { "command": ["npx", "lazy-mcp@latest", "npx", "mcp-remote@latest", "https://..."] },
    "grepai": { "command": ["npx", "lazy-mcp@latest", "grepai", "mcp-serve"] },
    "context7": { "command": ["npx", "-y", "@upstash/context7-mcp"] },
    "perplexity": { "command": ["npx", "-y", "@perplexity-ai/mcp-server"] }
  }
}
```

**After** (Consolidated into 1 multi-server proxy):
```json
{
  "mcp": {
    "lazy-mcp": {
      "type": "local",
      "command": ["npx", "lazy-mcp@latest", "--config", "~/.config/lazy-mcp/servers.json"],
      "enabled": true
    }
  }
}
```

Where `~/.config/lazy-mcp/servers.json` contains all 5 servers:
```json
{
  "servers": [
    { "name": "chrome-devtools", "description": "Chrome DevTools automation", "command": ["npx", "-y", "chrome-devtools-mcp@latest"] },
    { "name": "gitlab", "description": "GitLab API integration", "command": ["npx", "mcp-remote@latest", "https://..."] },
    { "name": "grepai", "description": "Search codebase", "command": ["grepai", "mcp-serve"] },
    { "name": "context7", "description": "Library documentation", "command": ["npx", "-y", "@upstash/context7-mcp"] },
    { "name": "perplexity", "description": "Web search", "command": ["npx", "-y", "@perplexity-ai/mcp-server"] }
  ]
}
```

**Result**: ~90% context reduction (from ~16K to ~1.5K tokens initially)

## Example

```bash
# Configure multiple MCP servers in servers.json, then:
npx lazy-mcp@latest --config ~/.config/lazy-mcp/servers.json
# Exposes: list_servers, list_commands, describe_commands, invoke_command (4 meta-tools)
# Instead of loading all tools from all servers upfront (~16K+ tokens),
# the agent discovers tools on-demand (~1.5K tokens initially)
```

## Development

```bash
npm install
npm run build
npm test
```

## Releases

Releases are fully automated via [semantic-release](https://semantic-release.gitbook.io/) on every push to `main`.

### How It Works

1. CI analyzes all commits since the last tag using [Conventional Commits]https://www.conventionalcommits.org/
2. Determines the next version (`feat` → minor bump, `fix`/`perf`/`chore`/`refactor`/`test` → patch bump)
3. Updates `package.json`, `CHANGELOG.md`, `VERSION`, and `RELEASE_NOTES.md`
4. Commits those files as `chore(release): X.Y.Z` and pushes a `vX.Y.Z` tag
5. Creates a GitLab Release with the generated release notes
6. The `vX.Y.Z` tag triggers a separate pipeline that publishes the package to npm automatically

No manual version bumping or tagging needed — just merge to `main` with conventional commit messages.

### Required CI/CD Variables

Four CI/CD variables must be configured (GitLab → Project → Settings → CI/CD → Variables):

| Variable | Description |
|----------|-------------|
| `GITLAB_RELEASE_TOKEN` | Project access token — pushes the release commit + tag to `main` and creates the GitLab Release |
| `NPM_TOKEN` | npm automation token — publishes the package to the npm registry on tag pipelines |
| `PYPI_TOKEN` | PyPI API token — publishes the package to PyPI on tag pipelines |
| `CARGO_TOKEN` | crates.io API token — publishes the crate to crates.io on tag pipelines |

#### `GITLAB_RELEASE_TOKEN`

**Creating the token** (GitLab → Project → Settings → Access Tokens):

| Setting | Value |
|---------|-------|
| Token name | `semantic-release-bot` (or any name) |
| Role | **Developer** (push to a protected branch should be configured separately) |
| Scopes | `api`, `write_repository` |

**Adding the variable:**

| Setting | Value |
|---------|-------|
| Key | `GITLAB_RELEASE_TOKEN` |
| Masked | ✅ Yes |
| Protected | ❌ No (must be available on the unprotected `main` pipeline) |

> **Note**: If `main` is a protected branch with push restrictions, the token's bot user must be added to the "Allowed to push" list under GitLab → Project → Settings → Repository → Protected branches.

#### `NPM_TOKEN`

**Creating the token** (npmjs.com → Account → Access Tokens → Generate New Token):

| Setting | Value |
|---------|-------|
| Token type | **Automation** (bypasses 2FA, suitable for CI) |

**Adding the variable:**

| Setting | Value |
|---------|-------|
| Key | `NPM_TOKEN` |
| Masked | ✅ Yes |
| Protected | ✅ Yes (only needed on tag pipelines, which are protected) |

#### `PYPI_TOKEN`

**Creating the token** (pypi.org → Account Settings → API tokens → Add API token):

| Setting | Value |
|---------|-------|
| Token name | `lazy-mcp-ci` (or any name) |
| Scope | **Project: lazy-mcp** (restrict to this project after first publish; use "Entire account" for the very first publish) |

**Adding the variable:**

| Setting | Value |
|---------|-------|
| Key | `PYPI_TOKEN` |
| Masked | ✅ Yes |
| Protected | ✅ Yes (only needed on tag pipelines, which are protected) |

#### `CARGO_TOKEN`

**Creating the token** (crates.io → Account Settings → API Tokens → New Token):

| Setting | Value |
|---------|-------|
| Token name | `lazy-mcp-ci` (or any name) |
| Scopes | `publish-new`, `publish-update` |

**Adding the variable:**

| Setting | Value |
|---------|-------|
| Key | `CARGO_TOKEN` |
| Masked | ✅ Yes |
| Protected | ✅ Yes (only needed on tag pipelines, which are protected) |

## Configuration Reference

### Server Configuration Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string || Unique server identifier |
| `description` | string || Human-readable description |
| `type` | "local" \| "remote" | Optional | Inferred from `url` (remote) or `command` (local) if omitted |
| `command` | string[] \| string | For local | Command to execute (array format recommended) |
| `args` | string[] | Optional | Arguments (only if command is string) |
| `url` | string | For remote | HTTP/HTTPS URL |
| `headers` | object | Optional | Static HTTP headers for remote servers |
| `oauth` | object | Optional | OAuth 2.0 config for remote servers (see below) |
| `env` | object | Optional | Environment variables (supports `${VAR}` expansion) |
| `enabled` | boolean | Optional | Enable/disable server (default: true) |
| `examples` | object[] | Optional | Usage examples shown in `list_servers` output |
| `tags` | string[] | Optional | Capability tags for filtering (e.g. `"api"`, `"browser"`) |

### OAuth 2.0 Authentication

lazy-mcp has built-in OAuth 2.0 + PKCE support for remote servers that require user authorization. It works without opening a browser automatically, making it suitable for sandboxed agent environments: when authentication is needed, lazy-mcp returns the authorization URL in the error message so the agent can present it to the user.

OAuth server endpoints are **discovered automatically** via RFC 8414 (`/.well-known/oauth-authorization-server`). Dynamic client registration (RFC 7591) is used when no `clientId` is provided.

Tokens are persisted to `~/.config/lazy-mcp/tokens.json` (mode `0600`) and refreshed automatically via `refresh_token` when available.

**Minimal config** (fully automatic — discovery + dynamic registration):
```json
{
  "name": "glean",
  "description": "Glean enterprise search",
  "url": "https://your-company.glean.com/mcp/default",
  "oauth": {}
}
```

**With a pre-registered client ID**:
```json
{
  "name": "glean",
  "description": "Glean enterprise search",
  "url": "https://your-company.glean.com/mcp/default",
  "oauth": {
    "clientId": "${GLEAN_CLIENT_ID}",
    "extraHeaders": { "X-Glean-Auth-Type": "OAUTH" }
  }
}
```

**`oauth` object fields:**

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `clientId` | string || OAuth client ID. If omitted, dynamic registration (RFC 7591) is attempted |
| `clientSecret` | string || Client secret (omit for public-client / PKCE-only flows) |
| `callbackPort` | number | `8947` | Local port for the OAuth redirect callback server |
| `extraHeaders` | object || Additional headers added to every authenticated request (e.g. `X-Glean-Auth-Type`) |

**How it works:**

1. Agent calls `invoke_command` (or `list_commands`) on an OAuth-protected server
2. lazy-mcp returns an `isError: true` response with the authorization URL
3. Agent presents the URL to the user: _"Open this URL to authorize Glean: https://..."_
4. User opens the URL in a browser and completes authorization
5. Browser redirects to `http://localhost:8947/callback` — lazy-mcp captures the token
6. Agent retries the original command — now succeeds transparently

### Command Format

**Recommended** (OpenCode-compatible):
```json
{
  "command": ["npx", "-y", "my-mcp-server", "--port", "3000"]
}
```

**Legacy** (still supported):
```json
{
  "command": "npx",
  "args": ["-y", "my-mcp-server", "--port", "3000"]
}
```

### Environment Variables

Use `${VAR_NAME}` to reference environment variables:

```json
{
  "env": {
    "API_KEY": "${MY_API_KEY}",
    "DEBUG": "true"
  },
  "headers": {
    "Authorization": "Bearer ${AUTH_TOKEN}"
  }
}
```

### Health Monitoring

lazy-mcp includes a background health monitor that probes all servers periodically. The monitor is **activity-driven**: it sleeps on startup and only begins probing after the first user tool call (`list_servers`, `list_commands`, etc.). After a configurable idle timeout (default: 5 minutes) with no tool calls, the monitor goes back to sleep. This prevents OAuth-protected servers (e.g. GitLab via `mcp-remote`) from opening browser windows when no one is using the tools.

Successful probes populate the discovery cache, so subsequent `list_commands` calls return instantly from cache.

**Top-level configuration** (in `servers.json`):

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `healthMonitor.enabled` | boolean | `true` | Enable/disable background health monitoring |
| `healthMonitor.interval` | number | `30000` | Interval between health checks (ms) |
| `healthMonitor.timeout` | number | `10000` | Timeout per server probe (ms) |
| `healthMonitor.idleTimeout` | number | `300000` | Stop probing after this much inactivity (ms). `0` = never sleep (legacy) |

To disable:
```json
{
  "servers": [...],
  "healthMonitor": { "enabled": false }
}
```

### Config Reload (SIGHUP)

You can reload the configuration without restarting the process by sending a `SIGHUP` signal:

```bash
kill -HUP $(pgrep -f lazy-mcp)
```

This will:
- Re-read and validate the config file
- Add newly configured servers (lazy connection on first use)
- Remove servers no longer in config (closes connections)
- Reconnect servers whose config changed (updated URL, env, etc.)
- Preserve unchanged servers (keeps existing connections and caches)
- Restart the health monitor and probe all servers

If the new config is invalid, the reload is rejected and the current config continues running. All reload activity is logged to stderr.

> **Note**: SIGHUP is not available on Windows.

## Benefits

- **90%+ context reduction** - From ~16K to ~1.5K tokens initially
- **Progressive tool discovery** - Only load schemas when needed
- **Multi-server aggregation** - Manage multiple MCP servers in one config
- **Batch discovery** - Discover multiple servers efficiently
- **Scales to hundreds** of commands without context bloat
- **Flexible configuration** - Enable/disable servers on demand
- **Environment variable support** - Secure credential management
- **Both local and remote** - Support for subprocess and HTTP servers
- **Health monitoring** - Background probes detect broken servers before you hit them

## Documentation

- **[CHANGELOG.md]./CHANGELOG.md** - Version history and release notes
- **[AGENTS.md]./AGENTS.md** - Development guide for AI coding agents (build commands, code style, testing patterns)
- **[doc/ARCHITECTURE.md]./doc/ARCHITECTURE.md** - Architecture overview and design patterns
- **[doc/CONTRIBUTING.md]./doc/CONTRIBUTING.md** - Contributing guide with common development tasks
- **[Configuration Reference]#configuration-reference** - Server configuration options (above)