Skip to content
Open
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
# stackprobe
Probe the tech stacks of any product

## MCP

Connect an agent to the hosted MCP server with an API key (see "Get a key" below):

```sh
claude mcp add --transport http stackprobe https://stackprobe.tech/mcp \
--header "Authorization: Bearer $STACKPROBE_KEY"
```

It has four tools: `scan_domain`, `get_scan`, `explain_detection` and `diff_scans`. `scan_domain` waits up to 25 seconds for a scan; if it's still running, call `get_scan` a little later. The limits are the same as the HTTP API's.

## HTTP API

Agents and scripts can use stackprobe over HTTP. Reading is free; starting scans needs a key, which you can create yourself.
Expand Down
1 change: 1 addition & 0 deletions apps/web/next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const nextConfig: NextConfig = {
'@drippa/stackprobe-browser-vercel-sandbox',
'@drippa/stackprobe-core',
'@drippa/stackprobe-decider-typesafe',
'@drippa/stackprobe-mcp',
'@drippa/stackprobe-store-postgres',
],
};
Expand Down
2 changes: 2 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
"@drippa/stackprobe-browser-vercel-sandbox": "workspace:*",
"@drippa/stackprobe-core": "workspace:*",
"@drippa/stackprobe-decider-typesafe": "workspace:*",
"@drippa/stackprobe-mcp": "workspace:*",
"@drippa/stackprobe-store-postgres": "workspace:*",
"@modelcontextprotocol/sdk": "^1.32.0",
"botid": "^1.5.11",
"next": "^16.3.8",
"react": "^19.3.0",
Expand Down
13 changes: 13 additions & 0 deletions apps/web/src/app/mcp/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { handleMcp } from '../../lib/mcp.ts';
import { getAccess, getStore } from '../../lib/services.ts';
import { startScanWorkflow } from '../../lib/start-workflow.ts';

// The remote MCP endpoint (Streamable HTTP). See lib/mcp.ts.
// scan_domain waits up to 25 s for a scan, so allow the function a minute.
export const maxDuration = 60;

function handle(request: Request): Promise<Response> {
return handleMcp(request, { store: getStore(), access: getAccess(), start: startScanWorkflow });
}

export { handle as DELETE, handle as GET, handle as POST };
10 changes: 10 additions & 0 deletions apps/web/src/lib/keys-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
type AccessDeps,
type ApiKeyRecord,
createApiKey,
findApiKey,
hashIp,
Expand Down Expand Up @@ -92,3 +93,12 @@ function bearer(authorization: string | null): string | null {
const match = authorization?.match(/^Bearer\s+(\S+)$/i);
return match?.[1] ?? null;
}

// The live API key an "Authorization: Bearer <key>" header names, or null.
export async function keyFromHeader(
authorization: string | null,
deps: AccessDeps,
): Promise<ApiKeyRecord | null> {
const key = bearer(authorization);
return key ? findApiKey(key, deps) : null;
}
121 changes: 121 additions & 0 deletions apps/web/src/lib/mcp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import {
createApiKey,
MemoryAccessStore,
MemoryStore,
type ScanRecord,
} from '@drippa/stackprobe-core';
import { runScanLocally } from '@drippa/stackprobe-mcp';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { afterEach, describe, expect, test } from 'vitest';
import { loadFixture, ReplayNet } from '../../../../packages/core/test/fixtures.ts';
import { handleMcp } from './mcp.ts';

const { recording } = loadFixture('vercel');
const clients: Client[] = [];
afterEach(async () => {
for (const client of clients.splice(0)) await client.close();
});

// An MCP client whose HTTP requests go straight to handleMcp. Scans "run as workflows" by
// replaying a recorded site in-process, or (running: true) never finish.
async function connect({ running = false, withKey = true } = {}) {
const store = new MemoryStore();
const access = new MemoryAccessStore();
const { key, record } = await createApiKey('ip-hash', { store: access });
const started: ScanRecord[] = [];
const deps = {
store,
access,
waitMs: running ? 2 : 25_000,
sleep: async () => {},
start: async (scan: ScanRecord) => {
started.push(scan);
if (!running) await runScanLocally(store, new ReplayNet(recording), scan);
},
};
const client = new Client({ name: 'test', version: '0' });
const transport = new StreamableHTTPClientTransport(new URL('https://stackprobe.test/mcp'), {
fetch: (url, init) => handleMcp(new Request(url, init), deps),
...(withKey ? { requestInit: { headers: { authorization: `Bearer ${key}` } } } : {}),
});
// The SDK's own transport, typed without exactOptionalPropertyTypes in mind.
await client.connect(transport as unknown as Transport);
clients.push(client);
return { client, store, access, started, subject: `key:${record.id}` as const };
}

async function call(client: Client, name: string, args: Record<string, unknown>) {
const result = (await client.callTool({ name, arguments: args })) as CallToolResult;
const text = result.content.map((part) => (part.type === 'text' ? part.text : '')).join('');
return { ...result, text };
}

describe('remote MCP at /mcp', () => {
test('lists the same four tools as the local server', async () => {
const { client } = await connect();
const { tools } = await client.listTools();
expect(tools.map((tool) => tool.name).sort()).toEqual([
'diff_scans',
'explain_detection',
'get_scan',
'scan_domain',
]);
});

test('scan_domain runs a hosted scan under the key, and get_scan reads it', async () => {
const { client, started, access, subject } = await connect();
const scanned = await call(client, 'scan_domain', { domain: recording.url });
expect(scanned.isError).toBeFalsy();
expect(scanned.structuredContent).toMatchObject({ status: 'done', reused: false });
expect(scanned.text).toContain('vercel');
expect(started).toHaveLength(1);
expect(await access.countNewScans(subject, '2000-01-01T00:00:00.000Z')).toBe(1);

const again = await call(client, 'scan_domain', { domain: recording.url });
expect(again.structuredContent).toMatchObject({ reused: true });
expect(started).toHaveLength(1);

const got = await call(client, 'get_scan', {
scan_id: (scanned.structuredContent as { scanId: string }).scanId,
});
expect(got.structuredContent).toMatchObject({ status: 'done' });
});

test('explain_detection and diff_scans work on hosted scans', async () => {
const { client } = await connect();
await call(client, 'scan_domain', { domain: recording.url });
const explained = await call(client, 'explain_detection', {
domain: recording.url,
tech: 'vercel',
});
expect(explained.isError).toBeFalsy();
expect(explained.text).toMatch(/vercel/i);
await call(client, 'scan_domain', { domain: recording.url, force: true });
const diff = await call(client, 'diff_scans', { domain: recording.url });
expect(diff.isError).toBeFalsy();
});

test('a scan still running after the wait comes back running, pointing to get_scan', async () => {
const { client } = await connect({ running: true });
const scanned = await call(client, 'scan_domain', { domain: 'acme.test' });
expect(scanned.structuredContent).toMatchObject({ status: 'running', report: null });
expect(scanned.text).toContain('Call get_scan again in a few seconds.');
});

test('the same limits as the HTTP API: the 11th new scan in a day is refused', async () => {
const { client } = await connect({ running: true });
for (let i = 0; i < 10; i++) {
expect((await call(client, 'scan_domain', { domain: `site${i}.test` })).isError).toBeFalsy();
}
const refused = await call(client, 'scan_domain', { domain: 'one-more.test' });
expect(refused.isError).toBe(true);
expect(refused.text).toMatch(/^Daily limit of 10 new scans reached/);
});

test('without a key: refused before any MCP traffic, saying how to get one', async () => {
await expect(connect({ withKey: false })).rejects.toThrow(/invalid_key.*POST \/api\/keys/);
});
});
62 changes: 62 additions & 0 deletions apps/web/src/lib/mcp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { createServer, type ScanStarter } from '@drippa/stackprobe-mcp';
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
import { invalidKey, keyFromHeader } from './keys-api.ts';
import { type ScansApiDeps, startKeyedScan } from './scans-api.ts';

// The remote MCP server at /mcp: the same four tools as the local stdio server (packages/mcp),
// with scans run as hosted workflow runs under the caller's API key and its limits.
// Stateless: each HTTP request gets its own server and transport, answered as plain JSON.

// How long scan_domain waits for a new scan before handing back the running one.
export const SCAN_WAIT_MS = 25_000;
const POLL_MS = 1_000;

export interface McpDeps extends Omit<ScansApiDeps, 'origin'> {
waitMs?: number;
sleep?: (ms: number) => Promise<void>;
}

export async function handleMcp(request: Request, deps: McpDeps): Promise<Response> {
const clock = deps.now ? { now: deps.now } : {};
const record = await keyFromHeader(request.headers.get('authorization'), {
store: deps.access,
...clock,
});
if (!record) {
const { status, body, headers } = invalidKey();
return Response.json(body, { status, headers });
}
await deps.access.recordUsage({
subject: `key:${record.id}`,
endpoint: `${request.method} /mcp`,
newScan: false,
});

const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));
const startScan: ScanStarter = async (domain, { force }) => {
const started = await startKeyedScan(
record,
domain,
{ force, endpoint: 'mcp scan_domain' },
deps,
);
// Give a new or running scan a little time, so most calls come back with the report.
let scan = started.scan;
for (let waited = 0; scan.status === 'running' && waited < (deps.waitMs ?? SCAN_WAIT_MS); ) {
await sleep(POLL_MS);
waited += POLL_MS;
scan = (await deps.store.getScan(scan.id)) ?? scan;
}
return { scan, reused: started.reused };
};

const server = createServer({ store: deps.store, startScan });
// No session id generator: stateless, as every request may land on a different function.
const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true });
await server.connect(transport);
try {
return await transport.handleRequest(request);
} finally {
await server.close();
}
}
70 changes: 43 additions & 27 deletions apps/web/src/lib/scans-api.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import {
type AccessStore,
type ApiKeyRecord,
assertAllowance,
findApiKey,
keySubject,
LimitError,
requestScan,
type ScanRecord,
type Store,
} from '@drippa/stackprobe-core';
import { type ApiResponse, invalidKey, limited } from './keys-api.ts';
import { type ApiResponse, invalidKey, keyFromHeader, limited } from './keys-api.ts';
import { reportJson } from './report-json.ts';

// The HTTP scan API, apart from Next's route handlers so it can be tested directly.
Expand Down Expand Up @@ -41,10 +41,8 @@ export async function createScanResponse(
): Promise<ApiResponse> {
const clock = deps.now ? { now: deps.now } : {};
const access = { store: deps.access, ...clock };
const key = authorization?.match(/^Bearer\s+(\S+)$/i)?.[1];
const record = key ? await findApiKey(key, access) : null;
const record = await keyFromHeader(authorization, access);
if (!record) return invalidKey();
const subject = keySubject(record);

let input: { domain?: unknown; force?: unknown };
try {
Expand All @@ -56,31 +54,14 @@ export async function createScanResponse(
return badRequest('invalid_domain', 'Send a JSON body like {"domain": "example.com"}.');
}

// Exactly one usage row per request: spent as a new scan, or logged as a reuse.
let spent = false;
try {
const scan = await requestScan(
const { scan, reused } = await startKeyedScan(
record,
input.domain,
{
store: deps.store,
start: deps.start,
...clock,
allowance: {
check: async () => {
await assertAllowance(subject, record.scansPerDay, access);
},
spend: async () => {
spent = true;
await deps.access.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: true });
},
},
},
{ force: input.force === true },
{ force: input.force === true, endpoint: 'POST /api/scans' },
deps,
);
if (!spent) {
await deps.access.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: false });
}
return scanResponse(scan, deps.origin, { reused: !spent, cache: false });
return scanResponse(scan, deps.origin, { reused, cache: false });
} catch (error) {
if (error instanceof TypeError) {
return badRequest('invalid_domain', `"${input.domain}" isn't a domain or URL.`);
Expand All @@ -90,6 +71,41 @@ export async function createScanResponse(
}
}

// Starts a scan with an API key, or returns the running or recent one, by requestScan's rules.
// New scans spend the key's daily allowance. Logs exactly one usage row: a new scan or a reuse.
// Throws TypeError for input that isn't a domain, LimitError at the limit.
export async function startKeyedScan(
record: ApiKeyRecord,
domain: string,
{ force, endpoint }: { force: boolean; endpoint: string },
deps: Pick<ScansApiDeps, 'store' | 'access' | 'start' | 'now'>,
): Promise<{ scan: ScanRecord; reused: boolean }> {
const clock = deps.now ? { now: deps.now } : {};
const access = { store: deps.access, ...clock };
const subject = keySubject(record);
let spent = false;
const scan = await requestScan(
domain,
{
store: deps.store,
start: deps.start,
...clock,
allowance: {
check: async () => {
await assertAllowance(subject, record.scansPerDay, access);
},
spend: async () => {
spent = true;
await deps.access.recordUsage({ subject, endpoint, newScan: true });
},
},
},
{ force },
);
if (!spent) await deps.access.recordUsage({ subject, endpoint, newScan: false });
return { scan, reused: !spent };
}

export async function getScanResponse(id: string, deps: ScansApiDeps): Promise<ApiResponse> {
const scan = await deps.store.getScan(id);
if (!scan) {
Expand Down
11 changes: 7 additions & 4 deletions packages/mcp/src/bin.ts
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,19 @@ import { NodeNet } from '@drippa/stackprobe-core/node';
import { deciderFromEnv } from '@drippa/stackprobe-decider-typesafe';
import { defaultDatabasePath, SqliteStore } from '@drippa/stackprobe-store-sqlite';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { createServer } from './server.ts';
import { createServer, localScanStarter } from './server.ts';

const store = new SqliteStore(process.env.STACKPROBE_DB || defaultDatabasePath());
const decider = deciderFromEnv();
const browser = await playwrightIfInstalled();
const server = createServer({
store,
net: new NodeNet(),
...(decider ? { decider } : {}),
...(browser ? { browser } : {}),
startScan: localScanStarter({
store,
net: new NodeNet(),
...(decider ? { decider } : {}),
...(browser ? { browser } : {}),
}),
});
process.on('exit', () => void browser?.close());
await server.connect(new StdioServerTransport());
4 changes: 2 additions & 2 deletions packages/mcp/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { runScanLocally } from './local-runner.ts';
export type { ServerOptions } from './server.ts';
export { createServer } from './server.ts';
export type { LocalScanOptions, ScanStarter, ServerOptions } from './server.ts';
export { createServer, localScanStarter } from './server.ts';
Loading
Loading