Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 47 additions & 5 deletions apps/docs/src/content/agents/mcp-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,37 @@ If you mount the devtools panel without the hub, at `/__ng-devtools/`, the endpo

The header value is the origin of your dev server. Every example below sets it.

### Send a token

If the hub asks for the one-time code, the HTTP endpoint also asks for a bearer token. Requests without the right token get `401`.

| Setup | Token required |
| --------------------------------------- | ------------------------------------------------------------------------------------------------ |
| [Express hub](/getting-started/express) | Yes, unless you pass `auth: false` or your own `mcp` option. |
| [Vite plugin](/getting-started/vite) | Only when the one-time code is on. See the plugin's [`auth` option](/getting-started/vite#auth). |

The hub prints a generated token in the terminal when it starts. The token changes on every restart. To keep the same token across restarts, set `NG_DEVTOOLS_MCP_TOKEN` in the environment of the server. The hub then uses that value and prints nothing.

Send the token in an `Authorization: Bearer <token>` header, next to the `Origin` header. If your setup needs no token, leave the `Authorization` header out.

The stdio server never needs a token.

### Add the HTTP endpoint to your client

```bash group="http" name="Claude Code" active
claude mcp add --transport http ng-devtools http://localhost:4000/__devframes/__mcp \
--header "Origin: http://localhost:4000"
```json group="http" name="Claude Code" active
// .mcp.json
{
"mcpServers": {
"ng-devtools": {
"type": "http",
"url": "http://localhost:4000/__devframes/__mcp",
"headers": {
"Authorization": "Bearer ${NG_DEVTOOLS_MCP_TOKEN}",
"Origin": "http://localhost:4000"
}
}
}
}
```

```json group="http" name="Cursor"
Expand All @@ -117,7 +143,10 @@ claude mcp add --transport http ng-devtools http://localhost:4000/__devframes/__
"mcpServers": {
"ng-devtools": {
"url": "http://localhost:4000/__devframes/__mcp",
"headers": {"Origin": "http://localhost:4000"}
"headers": {
"Authorization": "Bearer ${env:NG_DEVTOOLS_MCP_TOKEN}",
"Origin": "http://localhost:4000"
}
}
}
}
Expand All @@ -126,16 +155,29 @@ claude mcp add --transport http ng-devtools http://localhost:4000/__devframes/__
```json group="http" name="VS Code"
// .vscode/mcp.json
{
"inputs": [
{
"type": "promptString",
"id": "ng-devtools-token",
"description": "ng-devtools MCP token",
"password": true
}
],
"servers": {
"ng-devtools": {
"type": "http",
"url": "http://localhost:4000/__devframes/__mcp",
"headers": {"Origin": "http://localhost:4000"}
"headers": {
"Authorization": "Bearer ${input:ng-devtools-token}",
"Origin": "http://localhost:4000"
}
}
}
}
```

The Claude Code and Cursor examples read the token from `NG_DEVTOOLS_MCP_TOKEN`, so set the same value for the server and the client. VS Code asks for the token the first time it starts the server.

### Open the app in a browser

The live tools read what the page reports. Without an open page, they have nothing to answer with.
Expand Down
14 changes: 7 additions & 7 deletions apps/docs/src/content/getting-started/express.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,13 @@ With `ws: {sidecar: true}`, the WebSocket runs on its own port, picked automatic

`initNgDevtoolsHub()` accepts the options of `initHub()` from `@devframes/hub`, apart from `devframes` and `ui`. These are the ones you are most likely to set:

| Option | Default | What it does |
| ---------------- | ----------------- | --------------------------------------------------------------------------------------------- |
| `base` | `'/__devframes/'` | Where the hub is mounted. The devtools panel lives at `<base>ng-devtools/`. |
| `ws` | | `false` uses server-sent events only. `{ sidecar: true }` runs the WebSocket on its own port. |
| `auth` | on | `false` turns off the one-time code. |
| `allowedOrigins` | loopback origins | Extra origins allowed to open the WebSocket. `false` turns the origin check off. |
| `mcp` | `'auto'` | Mounts the MCP endpoint at `<base>__mcp` once agent tools exist. |
| Option | Default | What it does |
| ---------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `base` | `'/__devframes/'` | Where the hub is mounted. The devtools panel lives at `<base>ng-devtools/`. |
| `ws` | | `false` uses server-sent events only. `{ sidecar: true }` runs the WebSocket on its own port. |
| `auth` | on | `false` turns off the one-time code. |
| `allowedOrigins` | loopback origins | Extra origins allowed to open the WebSocket. `false` turns the origin check off. |
| `mcp` | a bearer token | Mounts the MCP endpoint at `<base>__mcp` and asks for a bearer token. With `auth: false` the default is `'auto'`: it mounts once agent tools exist and asks for no token. See [Send a token](/agents/mcp-server#send-a-token). |

### Access control

Expand Down
32 changes: 26 additions & 6 deletions apps/docs/src/content/getting-started/vite.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ It records Analog page renders, `load()` fetches, server functions and API calls

The plugin only answers requests from a loopback address (any `127.x.x.x` address or `::1`). Other requests to the devtools get `403` with the message "ng-devtools only answers requests from this machine." WebSocket upgrades follow the same rules.

The Vite plugin turns the one-time code off. The loopback and origin checks take its place. [Access and redaction](/security) covers both checks.
By default the plugin leaves the one-time code off, and the loopback and origin checks take its place. If `server.allowedHosts` or `allowedOrigins` allows a host that is not a loopback host, the plugin also asks for the code. See [`auth`](#auth). [Access and redaction](/security) covers every check.

## Options

Expand All @@ -99,11 +99,12 @@ ngDevtools({
});
```

| Option | Default | What it does |
| ---------------- | -------------------------------- | ------------------------------------------------------------------------ |
| `base` | `'/__devframes/'` | Where the hub is mounted. |
| `apiPrefix` | Analog's `apiPrefix`, or `'api'` | The prefix of your server routes, used to classify API calls. |
| `allowedOrigins` | none | Extra exact origins allowed to reach the devtools, for example a tunnel. |
| Option | Default | What it does |
| ---------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `base` | `'/__devframes/'` | Where the hub is mounted. |
| `apiPrefix` | Analog's `apiPrefix`, or `'api'` | The prefix of your server routes, used to classify API calls. |
| `allowedOrigins` | none | Extra exact origins allowed to reach the devtools, for example a tunnel. |
| `auth` | on if a non-loopback host or origin is allowed, otherwise off | Whether the devtools ask for the one-time code. |

### `base`

Expand All @@ -117,6 +118,23 @@ The plugin reads `apiPrefix` from your Analog config. Set it here only when the

Each entry is an exact origin, such as `https://tunnel.example`. The request itself must still come from a loopback address.

### `auth`

A tunnel forwards other people's requests to your machine, and those requests arrive from a loopback address. So the plugin turns the one-time code on when Vite's `server.allowedHosts` or `allowedOrigins` allows anything other than `localhost` or a loopback address (`allowedHosts: true` counts too). The server prints the code in the terminal, and a browser reads data only after it exchanges that code.

| Value | Effect |
| ------- | ------------------------------------------------------------------- |
| not set | The code is on only if a non-loopback host or origin is allowed. |
| `true` | The code is always on. |
| `false` | The code is always off. The loopback and origin checks still apply. |

If your tunnel rewrites the `Host` header to `localhost`, you don't list it in `server.allowedHosts`, so the plugin leaves the code off. Pass `auth: true`:

```ts
// vite.config.ts
ngDevtools({auth: true});
```

## Hostnames other than localhost

### Local hostnames
Expand Down Expand Up @@ -144,6 +162,8 @@ Add other origins with `allowedOrigins`:
ngDevtools({allowedOrigins: ['https://tunnel.example']});
```

A non-loopback entry in `server.allowedHosts` or `allowedOrigins` turns the one-time code on. See [`auth`](#auth).

## Angular CLI apps

<ngmd-alert severity="important">
Expand Down
22 changes: 17 additions & 5 deletions apps/docs/src/content/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ The devtools read your running app and send what they find to a server on your m

<ngmd-card-grid columns="2">
<ngmd-card icon="zap" title="Vite plugin">
Loopback requests only. A request that sends an <code>Origin</code> must come from a loopback host, a Chrome extension, <code>allowedOrigins</code> or Vite's <code>server.allowedHosts</code>.
Loopback requests only. A request that sends an <code>Origin</code> must come from a loopback host, a Chrome extension, <code>allowedOrigins</code> or Vite's <code>server.allowedHosts</code>. Asks for a one-time code when a non-loopback host or origin is allowed.
</ngmd-card>
<ngmd-card icon="layers" title="Express hub">
A one-time code and a loopback origin check. Both on by default.
Expand Down Expand Up @@ -59,10 +59,20 @@ export default defineConfig({
});
```

The Vite plugin turns the one-time code off. The loopback and origin checks take its place.
#### One-time code

The plugin's `auth` option decides whether the devtools also ask for the one-time code. The server prints the code in the terminal, and a browser reads data only after it exchanges that code.

| `auth` | One-time code |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| not set | On if `server.allowedHosts` or `allowedOrigins` allows a host other than `localhost` or a loopback address, otherwise off. `allowedHosts: true` turns it on. |
| `true` | Always on. |
| `false` | Always off. The loopback and origin checks still apply. |

With only loopback hosts allowed, the loopback and origin checks take the place of the code.

<ngmd-callout type="warning" title="Tunnels look local">
A tunnel client runs on your machine, so the requests it forwards come from a loopback address. Anyone who can reach the tunnel can then reach the devtools. Only allow a tunnel origin that only you can reach.
A tunnel client runs on your machine, so the requests it forwards come from a loopback address. That is why an allowed tunnel host or origin turns the one-time code on. If your tunnel rewrites the <code>Host</code> header to <code>localhost</code>, nothing in your config names the tunnel, so pass <code>auth: true</code>. Don't pass <code>auth: false</code> while a tunnel is allowed.
</ngmd-callout>

### Express hub
Expand Down Expand Up @@ -97,7 +107,9 @@ The CLI server binds to `localhost` and asks for a one-time code. `--host` chang

### MCP endpoint

The HTTP MCP endpoint answers only requests from a loopback address that carry a loopback `Origin` header. See [MCP server](/agents/mcp-server).
The HTTP MCP endpoint answers only requests from a loopback address that carry a loopback `Origin` header.

While the one-time code is on, the endpoint also asks for a bearer token. That is the Express hub by default, and the Vite plugin when its code is on. The hub prints a generated token when it starts. Set `NG_DEVTOOLS_MCP_TOKEN` to choose the token yourself. Requests without the right `Authorization: Bearer <token>` header get `401`. The stdio server needs no token. See [Send a token](/agents/mcp-server#send-a-token).

### Chrome extension

Expand Down Expand Up @@ -178,7 +190,7 @@ Response previews and TransferState values in the [SSR & HTTP tab](/inspectors/s
Open the app on <code>localhost</code>. Add other hostnames or origins one by one, only when you need them.
</ngmd-step>
<ngmd-step title="Leave the checks on">
Keep <code>auth</code> and the origin check on in the Express hub unless the machine is yours alone.
Keep <code>auth</code> and the origin check on in the Express hub unless the machine is yours alone. In the Vite plugin, don't pass <code>auth: false</code> while a tunnel host or origin is allowed.
</ngmd-step>
<ngmd-step title="Use test data">
Keep real credentials out of forms and API responses you inspect.
Expand Down
61 changes: 59 additions & 2 deletions packages/ng-devtools/src/__tests__/hub.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it } from 'vitest';
import { initNgDevtoolsHub } from '../hub.ts';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { initNgDevtoolsHub, type NgDevtoolsHubOptions } from '../hub.ts';
import { makeProject } from './analog-fixture.ts';

const hubs: { close: () => Promise<void> }[] = [];
Expand All @@ -21,7 +21,29 @@ async function boot(cwd: string) {
return { hub, ctx, docks };
}

async function bootMcp(options: NgDevtoolsHubOptions) {
const cwd = makeProject({ 'package.json': '{}' });
const hub = initNgDevtoolsHub({ cwd, ws: false, allowedOrigins: false, ...options });
hubs.push(hub);
await hub.ready;
return (token?: string) =>
hub.handler(
new Request('http://localhost/__devframes/__mcp', {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
origin: 'http://localhost:4000',
...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
},
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
}),
);
}

afterEach(async () => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
for (const hub of hubs.splice(0)) await hub.close();
});

Expand Down Expand Up @@ -56,3 +78,38 @@ describe('ng-devtools hub', () => {
expect(forms.markdown).toContain('No forms');
});
});

describe('ng-devtools hub MCP route', () => {
it('stays open when the hub runs without auth', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const mcp = await bootMcp({ auth: false });
expect((await mcp()).status).toBe(200);
expect(log.mock.calls.flat().join('\n')).not.toContain('MCP token');
});

it('requires the token from NG_DEVTOOLS_MCP_TOKEN when auth is on', async () => {
vi.stubEnv('NG_DEVTOOLS_MCP_TOKEN', 'env-secret');
const mcp = await bootMcp({});
expect((await mcp()).status).toBe(401);
expect((await mcp('wrong')).status).toBe(401);
const allowed = await mcp('env-secret');
expect(allowed.status).toBe(200);
expect(await allowed.text()).toContain('ng-devtools_get-routes');
});

it('prints a generated token when none is configured', async () => {
vi.stubEnv('NG_DEVTOOLS_MCP_TOKEN', '');
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const mcp = await bootMcp({ auth: true });
const token = /MCP token: (\S+)/.exec(log.mock.calls.flat().join('\n'))?.[1];
expect(token).toMatch(/^[\w-]{32}$/);
expect((await mcp()).status).toBe(401);
expect((await mcp(token)).status).toBe(200);
});

it('keeps an explicit mcp setting', async () => {
const mcp = await bootMcp({ auth: true, mcp: { authorization: 'own-secret' } });
expect((await mcp()).status).toBe(401);
expect((await mcp('own-secret')).status).toBe(200);
});
});
Loading
Loading