@registryhound/mcp 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Opimus LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @registryhound/mcp
2
+
3
+ [![Baffles78/registryhound-mcp MCP server](https://glama.ai/mcp/servers/Baffles78/registryhound-mcp/badges/score.svg)](https://glama.ai/mcp/servers/Baffles78/registryhound-mcp)
4
+
5
+ Official [Model Context Protocol](https://modelcontextprotocol.io) server for [RegistryHound](https://registryhound.com): search U.S. public government registries, read token-efficient entity dossiers, page through change-detection triggers and resolve one company across every registry.
6
+
7
+ Registries include FMCSA motor carriers (USDOT), the FAA aircraft registry (N-numbers), SEC EDGAR public companies (CIK / ticker), the CMS NPPES NPI registry, OSHA workplace inspections, USAspending federal awards and EPA ECHO facilities. New registries appear automatically: the tools are generated from the live [`/openapi.json`](https://registryhound.com/openapi.json) at start-up.
8
+
9
+ - Zero runtime dependencies (Node 18+ built-ins only)
10
+ - Transports: stdio (default), HTTP + SSE, Streamable HTTP
11
+ - API key or keyless [x402](https://registryhound.com/.well-known/x402.json) pay-per-request (USDC)
12
+
13
+ ## Try it on Glama
14
+
15
+ The [Glama listing](https://glama.ai/mcp/servers/Baffles78/registryhound-mcp) lets you browse the tools, check the quality score and test the server online with the [MCP Inspector](https://glama.ai/mcp/inspector). The server is also listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=registryhound) as `io.github.Baffles78/registryhound`.
16
+
17
+ ## Tools
18
+
19
+ | Tool | What it does | Cost |
20
+ |---|---|---|
21
+ | `search_registries` | Search every registry (or one) by name or id. Returns market, id, name, city, state, URL; exact id matches first. | Free |
22
+ | `get_entity` | One record. `format: "markdown"` (default) returns a compact dossier: title, canonical URL, official verification link, key fields table, recent change triggers, disclaimer. `format: "json"` returns structured fields. `live: true` uses the metered, uncached API. | Free (`live`: paid) |
23
+ | `get_triggers` | Change-detection feed for one registry: new registrations, ownership transfers, status changes, filings, penalties, award changes. Filters: `since`, `until`, `type`, `state`, `limit`, `cursor`. | Paid |
24
+ | `resolve_entity` | Link one company across all registries by EIN / UEI / CIK / USDOT / FRN and normalized legal name + state. | Paid (Full API plan) |
25
+
26
+ ## Install
27
+
28
+ ### Claude Desktop / Claude Code / Cursor (stdio)
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "registryhound": {
34
+ "command": "npx",
35
+ "args": ["-y", "@registryhound/mcp"],
36
+ "env": { "REGISTRYHOUND_API_KEY": "rh_live_..." }
37
+ }
38
+ }
39
+ }
40
+ ```
41
+
42
+ Claude Code: `claude mcp add registryhound -e REGISTRYHOUND_API_KEY=rh_live_... -- npx -y @registryhound/mcp`
43
+
44
+ Leave `REGISTRYHOUND_API_KEY` out to use only the free tools plus x402 pay-per-request.
45
+
46
+ ### HTTP (SSE and Streamable HTTP)
47
+
48
+ ```bash
49
+ npx -y @registryhound/mcp --sse --port 3333
50
+ # GET http://127.0.0.1:3333/sse legacy HTTP+SSE (then POST /messages?sessionId=...)
51
+ # POST http://127.0.0.1:3333/mcp Streamable HTTP (JSON responses)
52
+ ```
53
+
54
+ The HTTP transport binds to `127.0.0.1` by default and rejects browser origins other than localhost. Use `--host 0.0.0.0` only behind your own auth, and set `MCP_HTTP_TOKEN` to require `Authorization: Bearer <token>`.
55
+
56
+ ## Configuration
57
+
58
+ | Variable | Default | |
59
+ |---|---|---|
60
+ | `REGISTRYHOUND_API_KEY` | (none) | `x-api-key` for paid tools. Plans: https://registryhound.com/pricing. Never sent to free endpoints. |
61
+ | `REGISTRYHOUND_BASE_URL` | `https://registryhound.com` | Server to query (also `--base-url`). |
62
+ | `REGISTRYHOUND_OPENAPI_URL` | `<base>/openapi.json` | Spec the tools are generated from. |
63
+ | `REGISTRYHOUND_TIMEOUT_MS` | `20000` | Per-request timeout. |
64
+ | `MCP_HTTP_TOKEN` | (none) | Bearer token required on the HTTP transport. |
65
+ | `MCP_ALLOWED_ORIGINS` | (none) | Extra browser origins allowed on the HTTP transport (comma list). |
66
+
67
+ `npx -y @registryhound/mcp --list-tools` prints the generated tool schemas.
68
+
69
+ ## Paying per request with x402
70
+
71
+ Without an API key, `get_triggers`, `resolve_entity` and `get_entity` with `live: true` return an error result that contains the decoded `PAYMENT-REQUIRED` offer (x402 v2: network, USDC asset, amount, pay-to address) in both the text and `structuredContent.payment_required`. An x402-capable wallet signs one offer; call the same tool again with `payment_signature` set to the base64 `PAYMENT-SIGNATURE` value (and optionally `idempotency_key`). The result then ends with the decoded `PAYMENT-RESPONSE` settlement receipt. A retried signature is served from the receipt cache and never charged twice. Requests that return nothing (404, empty resolve) are not charged.
72
+
73
+ ## Use as a library
74
+
75
+ ```js
76
+ import { RegistryHoundMcp, loadSettings, runStdio } from '@registryhound/mcp';
77
+ const mcp = new RegistryHoundMcp(loadSettings());
78
+ const res = await mcp.handle({ jsonrpc: '2.0', id: 1, method: 'tools/call',
79
+ params: { name: 'get_entity', arguments: { market: 'sec', id: '0000320193' } } });
80
+ ```
81
+
82
+ ## Data and compliance
83
+
84
+ RegistryHound republishes public U.S. government records. It is **not a consumer reporting agency**: results are not consumer reports under the FCRA and must not be used for credit, insurance, employment, housing or any other FCRA purpose. Records can be out of date; every dossier links the official source for verification. Records whose owners opted out show contact fields as "Withheld".
85
+
86
+ Operated by Opimus LLC. Docs: https://registryhound.com/docs · Agent docs: https://registryhound.com/llms-full.txt
87
+
88
+ ## Development
89
+
90
+ ```bash
91
+ npm install && npm run build && npm test
92
+ ```
93
+
94
+ License: MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ // registryhound-mcp [--sse] [--port 3333] [--host 127.0.0.1] [--base-url URL] [--list-tools]
3
+ import { loadSettings, VERSION } from './config.js';
4
+ import { RegistryHoundMcp } from './server.js';
5
+ import { runStdio, startHttp } from './transports.js';
6
+ const argv = process.argv.slice(2);
7
+ const flag = (n) => argv.includes(`--${n}`);
8
+ const opt = (n) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : undefined; };
9
+ const log = (m) => process.stderr.write(`[registryhound-mcp] ${m}\n`); // stdout is the protocol channel
10
+ if (flag('help') || flag('h')) {
11
+ process.stdout.write(`registryhound-mcp ${VERSION}
12
+
13
+ Usage:
14
+ registryhound-mcp stdio transport (default; for Claude Desktop, Claude Code, Cursor, ...)
15
+ registryhound-mcp --sse [--port 3333] [--host 127.0.0.1]
16
+ HTTP: GET /sse + POST /messages (SSE) and POST /mcp (Streamable HTTP)
17
+ registryhound-mcp --list-tools print the generated tool schemas and exit
18
+
19
+ Environment:
20
+ REGISTRYHOUND_API_KEY x-api-key for paid tools (without it, paid tools return x402 payment offers)
21
+ REGISTRYHOUND_BASE_URL default https://registryhound.com
22
+ REGISTRYHOUND_OPENAPI_URL default <base>/openapi.json
23
+ REGISTRYHOUND_TIMEOUT_MS default 20000
24
+ MCP_HTTP_TOKEN require "Authorization: Bearer <token>" on the HTTP transport
25
+ MCP_ALLOWED_ORIGINS comma list of extra browser origins allowed on the HTTP transport
26
+ `);
27
+ process.exit(0);
28
+ }
29
+ if (flag('version')) {
30
+ process.stdout.write(`${VERSION}\n`);
31
+ process.exit(0);
32
+ }
33
+ const settings = loadSettings(process.env, { ...(opt('base-url') ? { baseUrl: opt('base-url') } : {}) });
34
+ const mcp = new RegistryHoundMcp(settings, fetch, log);
35
+ if (flag('list-tools')) {
36
+ const tools = await mcp.getTools();
37
+ process.stdout.write(JSON.stringify(tools.map(t => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })), null, 2) + '\n');
38
+ process.exit(0);
39
+ }
40
+ if (flag('sse') || flag('http')) {
41
+ const port = Number(opt('port') ?? process.env.PORT ?? 3333);
42
+ const host = opt('host') ?? '127.0.0.1';
43
+ await startHttp(mcp, {
44
+ host, port,
45
+ token: process.env.MCP_HTTP_TOKEN || undefined,
46
+ allowedOrigins: (process.env.MCP_ALLOWED_ORIGINS ?? '').split(',').map(s => s.trim()).filter(Boolean),
47
+ });
48
+ log(`listening on http://${host}:${port} (GET /sse, POST /mcp) for ${settings.baseUrl}${settings.apiKey ? ' with API key' : ' (keyless: x402 offers)'}`);
49
+ }
50
+ else {
51
+ log(`stdio ready for ${settings.baseUrl}${settings.apiKey ? ' with API key' : ' (keyless: x402 offers)'}`);
52
+ await runStdio(mcp);
53
+ }
@@ -0,0 +1,12 @@
1
+ export declare const VERSION = "0.1.0";
2
+ export interface Settings {
3
+ /** Public site, e.g. https://registryhound.com (no trailing slash) */
4
+ baseUrl: string;
5
+ /** OpenAPI document the tools are generated from */
6
+ openapiUrl: string;
7
+ /** x-api-key for the paid API; empty = keyless (x402 offers are surfaced instead) */
8
+ apiKey: string;
9
+ timeoutMs: number;
10
+ userAgent: string;
11
+ }
12
+ export declare function loadSettings(env?: NodeJS.ProcessEnv, over?: Partial<Settings>): Settings;
package/dist/config.js ADDED
@@ -0,0 +1,12 @@
1
+ // Runtime settings, all from the environment (or CLI flags that override them).
2
+ export const VERSION = '0.1.0';
3
+ export function loadSettings(env = process.env, over = {}) {
4
+ const baseUrl = (over.baseUrl ?? env.REGISTRYHOUND_BASE_URL ?? 'https://registryhound.com').replace(/\/+$/, '');
5
+ return {
6
+ baseUrl,
7
+ openapiUrl: over.openapiUrl ?? env.REGISTRYHOUND_OPENAPI_URL ?? `${baseUrl}/openapi.json`,
8
+ apiKey: (over.apiKey ?? env.REGISTRYHOUND_API_KEY ?? '').trim(),
9
+ timeoutMs: over.timeoutMs ?? (Number(env.REGISTRYHOUND_TIMEOUT_MS) || 20_000),
10
+ userAgent: over.userAgent ?? `registryhound-mcp/${VERSION} (+https://registryhound.com/docs)`,
11
+ };
12
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { Settings } from './config.js';
2
+ export interface CallResult {
3
+ ok: boolean;
4
+ status: number;
5
+ contentType: string;
6
+ body: string;
7
+ /** Decoded PAYMENT-REQUIRED (x402 v2) when the server answered 402 */
8
+ paymentRequired?: unknown;
9
+ /** Decoded PAYMENT-RESPONSE (settlement receipt) after a paid x402 call */
10
+ paymentResponse?: unknown;
11
+ nextCursor?: string;
12
+ rateLimit?: {
13
+ limit?: string;
14
+ remaining?: string;
15
+ reset?: string;
16
+ };
17
+ }
18
+ /** base64 JSON header (x402 v2) -> object; undefined when absent or malformed. */
19
+ export declare function decodeB64Json(v: string | null | undefined): unknown;
20
+ export interface CallOptions {
21
+ accept?: string;
22
+ /** Send x-api-key (paid endpoints only; never sent to free routes) */
23
+ auth?: boolean;
24
+ paymentSignature?: string;
25
+ idempotencyKey?: string;
26
+ }
27
+ export declare function call(s: Settings, url: string, o?: CallOptions, fetchImpl?: typeof fetch): Promise<CallResult>;
package/dist/http.js ADDED
@@ -0,0 +1,43 @@
1
+ /** base64 JSON header (x402 v2) -> object; undefined when absent or malformed. */
2
+ export function decodeB64Json(v) {
3
+ if (!v)
4
+ return undefined;
5
+ try {
6
+ return JSON.parse(Buffer.from(v, 'base64').toString('utf8'));
7
+ }
8
+ catch {
9
+ return undefined;
10
+ }
11
+ }
12
+ export async function call(s, url, o = {}, fetchImpl = fetch) {
13
+ const headers = { 'user-agent': s.userAgent, accept: o.accept ?? 'application/json' };
14
+ if (o.auth && s.apiKey)
15
+ headers['x-api-key'] = s.apiKey;
16
+ if (o.paymentSignature)
17
+ headers['payment-signature'] = o.paymentSignature;
18
+ if (o.idempotencyKey)
19
+ headers['idempotency-key'] = o.idempotencyKey;
20
+ const ctrl = new AbortController();
21
+ const timer = setTimeout(() => ctrl.abort(), s.timeoutMs);
22
+ try {
23
+ const r = await fetchImpl(url, { headers, signal: ctrl.signal, redirect: 'follow' });
24
+ const body = await r.text();
25
+ const h = r.headers;
26
+ let paymentRequired = r.status === 402 ? decodeB64Json(h.get('payment-required')) : undefined;
27
+ if (r.status === 402 && paymentRequired === undefined) {
28
+ try {
29
+ paymentRequired = JSON.parse(body);
30
+ }
31
+ catch { /* not JSON */ }
32
+ }
33
+ const rl = h.get('x-ratelimit-limit') ? { limit: h.get('x-ratelimit-limit') ?? undefined, remaining: h.get('x-ratelimit-remaining') ?? undefined, reset: h.get('x-ratelimit-reset') ?? undefined } : undefined;
34
+ return {
35
+ ok: r.ok, status: r.status, contentType: h.get('content-type') ?? '', body,
36
+ paymentRequired, paymentResponse: decodeB64Json(h.get('payment-response')),
37
+ nextCursor: h.get('x-next-cursor') ?? undefined, rateLimit: rl,
38
+ };
39
+ }
40
+ finally {
41
+ clearTimeout(timer);
42
+ }
43
+ }
@@ -0,0 +1,5 @@
1
+ export { loadSettings, VERSION, type Settings } from './config.js';
2
+ export { RegistryHoundMcp, PROTOCOL_VERSIONS, type RpcMessage } from './server.js';
3
+ export { buildTools, loadSpec, marketsFrom, operations, paidResult, type Tool, type ToolResult } from './tools.js';
4
+ export { call, decodeB64Json, type CallResult } from './http.js';
5
+ export { runStdio, startHttp, type HttpOptions } from './transports.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // Library entry: embed the RegistryHound MCP server in your own process.
2
+ export { loadSettings, VERSION } from './config.js';
3
+ export { RegistryHoundMcp, PROTOCOL_VERSIONS } from './server.js';
4
+ export { buildTools, loadSpec, marketsFrom, operations, paidResult } from './tools.js';
5
+ export { call, decodeB64Json } from './http.js';
6
+ export { runStdio, startHttp } from './transports.js';
@@ -0,0 +1,26 @@
1
+ import { type Settings } from './config.js';
2
+ import { type Tool } from './tools.js';
3
+ type Json = Record<string, any>;
4
+ export declare const PROTOCOL_VERSIONS: string[];
5
+ export interface RpcMessage {
6
+ jsonrpc: '2.0';
7
+ id?: string | number | null;
8
+ method?: string;
9
+ params?: Json;
10
+ result?: unknown;
11
+ error?: unknown;
12
+ }
13
+ export declare class RegistryHoundMcp {
14
+ readonly settings: Settings;
15
+ private readonly fetchImpl;
16
+ private readonly log;
17
+ private tools;
18
+ constructor(settings: Settings, fetchImpl?: typeof fetch, log?: (m: string) => void);
19
+ /** Tools are generated once from /openapi.json (lazily, so start-up never blocks on the network). */
20
+ getTools(): Promise<Tool[]>;
21
+ /** Handle one message or a batch. Returns the response(s), or null for notifications / responses. */
22
+ handle(msg: RpcMessage | RpcMessage[]): Promise<RpcMessage | RpcMessage[] | null>;
23
+ private handleOne;
24
+ private dispatch;
25
+ }
26
+ export {};
package/dist/server.js ADDED
@@ -0,0 +1,90 @@
1
+ // Transport-agnostic MCP (JSON-RPC 2.0) handler: initialize, ping, tools/list, tools/call.
2
+ import { VERSION } from './config.js';
3
+ import { buildTools, loadSpec } from './tools.js';
4
+ export const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
5
+ const INSTRUCTIONS = 'RegistryHound republishes U.S. public government registries (motor carriers, aircraft, SEC filers, NPI providers, OSHA inspections, federal awards and more) and detects changes in them. Typical flow: search_registries -> get_entity (Markdown dossier, free) -> get_triggers / resolve_entity (paid: API key or x402). Not a consumer reporting agency: never use results for FCRA purposes (credit, insurance, employment, housing); verify with the linked primary source.';
6
+ export class RegistryHoundMcp {
7
+ settings;
8
+ fetchImpl;
9
+ log;
10
+ tools = null;
11
+ constructor(settings, fetchImpl = fetch, log = () => { }) {
12
+ this.settings = settings;
13
+ this.fetchImpl = fetchImpl;
14
+ this.log = log;
15
+ }
16
+ /** Tools are generated once from /openapi.json (lazily, so start-up never blocks on the network). */
17
+ getTools() {
18
+ if (!this.tools) {
19
+ this.tools = loadSpec(this.settings, this.fetchImpl).then(spec => {
20
+ this.log(spec ? `loaded ${this.settings.openapiUrl}` : `could not load ${this.settings.openapiUrl}; using built-in tool schemas`);
21
+ return buildTools(spec, this.settings, this.fetchImpl);
22
+ });
23
+ }
24
+ return this.tools;
25
+ }
26
+ /** Handle one message or a batch. Returns the response(s), or null for notifications / responses. */
27
+ async handle(msg) {
28
+ if (Array.isArray(msg)) {
29
+ const out = (await Promise.all(msg.map(m => this.handleOne(m)))).filter((m) => m !== null);
30
+ return out.length ? out : null;
31
+ }
32
+ return this.handleOne(msg);
33
+ }
34
+ async handleOne(m) {
35
+ if (!m || typeof m !== 'object' || m.jsonrpc !== '2.0')
36
+ return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } };
37
+ if (!m.method)
38
+ return null; // a response to us (we never send requests)
39
+ const isNotification = m.id === undefined;
40
+ try {
41
+ const result = await this.dispatch(m.method, m.params ?? {});
42
+ return isNotification ? null : { jsonrpc: '2.0', id: m.id ?? null, result };
43
+ }
44
+ catch (e) {
45
+ if (isNotification)
46
+ return null;
47
+ return { jsonrpc: '2.0', id: m.id ?? null, error: { code: e?.code ?? -32603, message: e?.message ?? 'Internal error' } };
48
+ }
49
+ }
50
+ async dispatch(method, params) {
51
+ switch (method) {
52
+ case 'initialize': {
53
+ const asked = String(params.protocolVersion ?? '');
54
+ return {
55
+ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
56
+ capabilities: { tools: { listChanged: false } },
57
+ serverInfo: { name: 'registryhound', title: 'RegistryHound', version: VERSION },
58
+ instructions: INSTRUCTIONS,
59
+ };
60
+ }
61
+ case 'ping': return {};
62
+ case 'notifications/initialized':
63
+ case 'notifications/cancelled':
64
+ return {};
65
+ case 'tools/list': {
66
+ const tools = await this.getTools();
67
+ return { tools: tools.map(t => ({ name: t.name, title: t.title, description: t.description, inputSchema: t.inputSchema, annotations: t.annotations })) };
68
+ }
69
+ case 'tools/call': {
70
+ const tools = await this.getTools();
71
+ const tool = tools.find(t => t.name === params.name);
72
+ if (!tool)
73
+ throw Object.assign(new Error(`Unknown tool: ${params.name}`), { code: -32602 });
74
+ const args = (params.arguments ?? {});
75
+ for (const r of (tool.inputSchema.required ?? []))
76
+ if (args[r] === undefined || args[r] === '')
77
+ return { content: [{ type: 'text', text: `Missing required argument: ${r}` }], isError: true };
78
+ try {
79
+ return await tool.run(args);
80
+ }
81
+ catch (e) {
82
+ const msg = e?.name === 'AbortError' ? `Timed out after ${this.settings.timeoutMs} ms` : String(e?.message ?? e);
83
+ return { content: [{ type: 'text', text: `Request failed: ${msg}` }], isError: true };
84
+ }
85
+ }
86
+ default:
87
+ throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,34 @@
1
+ import type { Settings } from './config.js';
2
+ import { type CallResult } from './http.js';
3
+ type Json = Record<string, any>;
4
+ export type JsonSchema = Json;
5
+ export interface ToolResult {
6
+ content: {
7
+ type: 'text';
8
+ text: string;
9
+ }[];
10
+ isError?: boolean;
11
+ structuredContent?: Json;
12
+ }
13
+ export interface Tool {
14
+ name: string;
15
+ title: string;
16
+ description: string;
17
+ inputSchema: JsonSchema;
18
+ annotations: Json;
19
+ run(args: Json): Promise<ToolResult>;
20
+ }
21
+ export declare const FALLBACK_MARKETS: string[];
22
+ interface Op {
23
+ path: string;
24
+ method: string;
25
+ op: Json;
26
+ }
27
+ export declare function operations(spec: Json | null): Op[];
28
+ export declare function marketsFrom(spec: Json | null): string[];
29
+ /** Format a paid-endpoint response, surfacing x402 offers and receipts. */
30
+ export declare function paidResult(s: Settings, r: CallResult): ToolResult;
31
+ export declare function buildTools(spec: Json | null, s: Settings, fetchImpl?: typeof fetch): Tool[];
32
+ /** Fetch the OpenAPI document; null on any failure (tools fall back to built-in schemas). */
33
+ export declare function loadSpec(s: Settings, fetchImpl?: typeof fetch): Promise<Json | null>;
34
+ export {};
package/dist/tools.js ADDED
@@ -0,0 +1,213 @@
1
+ import { call } from './http.js';
2
+ export const FALLBACK_MARKETS = ['fmcsa', 'faa', 'sec', 'cms', 'osha', 'grants'];
3
+ const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
4
+ export function operations(spec) {
5
+ const out = [];
6
+ for (const [path, item] of Object.entries(spec?.paths ?? {}))
7
+ for (const m of HTTP_METHODS)
8
+ if (item?.[m])
9
+ out.push({ path, method: m, op: item[m] });
10
+ return out;
11
+ }
12
+ const byId = (spec, id) => operations(spec).find(o => o.op.operationId === id);
13
+ /** Resolve a local $ref ("#/components/...") one level deep. */
14
+ function deref(spec, v) {
15
+ if (!v?.$ref || typeof v.$ref !== 'string' || !v.$ref.startsWith('#/'))
16
+ return v;
17
+ return v.$ref.slice(2).split('/').reduce((o, k) => o?.[k], spec) ?? v;
18
+ }
19
+ /** OpenAPI parameter -> JSON Schema property (examples and descriptions kept for the model). */
20
+ function paramProp(spec, p) {
21
+ const schema = { ...deref(spec, p.schema ?? {}) };
22
+ delete schema.example;
23
+ const prop = { ...schema };
24
+ if (p.description)
25
+ prop.description = p.description;
26
+ if (p.example !== undefined)
27
+ prop.examples = [p.example];
28
+ return prop;
29
+ }
30
+ function params(spec, op, where) {
31
+ return (op?.op.parameters ?? []).map(p => deref(spec, p)).filter(p => p.in === where);
32
+ }
33
+ export function marketsFrom(spec) {
34
+ for (const o of operations(spec)) {
35
+ const m = params(spec, o, 'path').find(p => p.name === 'market');
36
+ const e = deref(spec, m?.schema ?? {})?.enum;
37
+ if (Array.isArray(e) && e.length && o.path.includes('/entity/'))
38
+ return e.map(String);
39
+ }
40
+ return FALLBACK_MARKETS;
41
+ }
42
+ /** Requests always go to the configured base URL (REGISTRYHOUND_BASE_URL), so staging/self-hosted servers work. */
43
+ const serverUrl = (_spec, s) => s.baseUrl;
44
+ const fill = (path, vals) => path.replace(/\{(\w+)\}/g, (_, k) => encodeURIComponent(vals[k] ?? ''));
45
+ const qs = (args, names) => {
46
+ const u = new URLSearchParams();
47
+ for (const n of names) {
48
+ const v = args[n];
49
+ if (v === undefined || v === null || v === '')
50
+ continue;
51
+ u.set(n, Array.isArray(v) ? v.join(',') : String(v));
52
+ }
53
+ const s = u.toString();
54
+ return s ? `?${s}` : '';
55
+ };
56
+ const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], ...(isError ? { isError } : {}) });
57
+ /** Compact JSON bodies (fewer tokens); pass Markdown / CSV / text through. */
58
+ function bodyText(r) {
59
+ if (r.contentType.includes('json')) {
60
+ try {
61
+ return JSON.stringify(JSON.parse(r.body));
62
+ }
63
+ catch { /* fall through */ }
64
+ }
65
+ return r.body;
66
+ }
67
+ const PAYMENT_PROPS = {
68
+ payment_signature: { type: 'string', description: 'x402 v2 keyless payment: base64 JSON PaymentPayload signed for one of the offers returned in a previous payment_required result. Sent as the PAYMENT-SIGNATURE header. Not needed when REGISTRYHOUND_API_KEY is set.' },
69
+ idempotency_key: { type: 'string', description: 'Optional Idempotency-Key so a retried paid call is served from the receipt cache instead of charging again.' },
70
+ };
71
+ /** Format a paid-endpoint response, surfacing x402 offers and receipts. */
72
+ export function paidResult(s, r) {
73
+ if (r.status === 402) {
74
+ const pr = r.paymentRequired;
75
+ const how = s.apiKey
76
+ ? 'The API key was not accepted for this call.'
77
+ : `No REGISTRYHOUND_API_KEY is set. Either set one (plans: ${s.baseUrl}/pricing) or pay per request with x402 (USDC): sign one of the "accepts" offers below with an x402 v2 wallet and call this tool again with payment_signature set to the base64 PAYMENT-SIGNATURE value.`;
78
+ return {
79
+ content: [{ type: 'text', text: `Payment required (HTTP 402, x402 v2). ${how}\nPAYMENT-REQUIRED: ${JSON.stringify(pr ?? null)}` }],
80
+ structuredContent: { payment_required: pr ?? null, discovery: `${s.baseUrl}/.well-known/x402.json` },
81
+ isError: true,
82
+ };
83
+ }
84
+ if (!r.ok) {
85
+ const hint = r.status === 401 ? (s.apiKey ? ' The API key is invalid or inactive.' : ` Set REGISTRYHOUND_API_KEY (plans: ${s.baseUrl}/pricing).`)
86
+ : r.status === 403 ? ' This key\'s plan does not cover this request (Single Scope keys cover one registry and no cross-registry calls).'
87
+ : r.status === 429 ? ' Rate limited; retry after the reset.' : '';
88
+ return text(`HTTP ${r.status}.${hint}\n${bodyText(r)}`, true);
89
+ }
90
+ const meta = [];
91
+ if (r.nextCursor)
92
+ meta.push(`next_cursor: ${r.nextCursor}`);
93
+ if (r.paymentResponse !== undefined)
94
+ meta.push(`PAYMENT-RESPONSE: ${JSON.stringify(r.paymentResponse)}`);
95
+ if (r.rateLimit?.remaining !== undefined)
96
+ meta.push(`rate limit remaining: ${r.rateLimit.remaining}/${r.rateLimit.limit}`);
97
+ return text(bodyText(r) + (meta.length ? `\n\n${meta.join('\n')}` : ''));
98
+ }
99
+ function freeResult(r) {
100
+ if (r.ok)
101
+ return text(bodyText(r));
102
+ return text(`HTTP ${r.status}${r.status === 404 ? ' (not found)' : r.status === 429 ? ' (rate limited, retry in a minute)' : ''}.\n${bodyText(r)}`, true);
103
+ }
104
+ const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
105
+ export function buildTools(spec, s, fetchImpl = fetch) {
106
+ const markets = marketsFrom(spec);
107
+ const server = serverUrl(spec, s);
108
+ const marketProp = { type: 'string', enum: markets, description: `Registry slug, one of: ${markets.join(', ')}.` };
109
+ const tools = [];
110
+ // --- search_registries (free) ---
111
+ const searchOp = byId(spec, 'searchRegistries');
112
+ const searchParams = params(spec, searchOp, 'query');
113
+ const searchProps = searchParams.length
114
+ ? Object.fromEntries(searchParams.map(p => [p.name, paramProp(spec, p)]))
115
+ : { q: { type: 'string', minLength: 2, description: 'Entity name or registry id' }, market: { type: 'string', enum: ['all', ...markets] }, limit: { type: 'integer', minimum: 1 } };
116
+ const searchRequired = searchParams.length ? searchParams.filter(p => p.required).map(p => p.name) : ['q'];
117
+ tools.push({
118
+ name: 'search_registries',
119
+ title: 'Search public registries',
120
+ description: `Search RegistryHound's U.S. public registries (${markets.join(', ')}) by entity name or registry id. Returns market, id, name, city, state and the entity URL for each match; exact id matches come first. Free. Follow up with get_entity.`,
121
+ inputSchema: { type: 'object', properties: searchProps, required: searchRequired, additionalProperties: false },
122
+ annotations: { title: 'Search public registries', ...READ_ONLY },
123
+ run: async (a) => freeResult(await call(s, `${server}${searchOp?.path ?? '/search.json'}${qs(a, Object.keys(searchProps))}`, {}, fetchImpl)),
124
+ });
125
+ // --- get_entity (free Markdown / JSON, or metered live API) ---
126
+ const mdOp = byId(spec, 'getEntityMarkdown');
127
+ const jsonOp = byId(spec, 'getEntityPublic');
128
+ const paidEntity = byId(spec, 'getEntity');
129
+ const idParam = params(spec, jsonOp ?? paidEntity, 'path').find(p => p.name === 'id');
130
+ tools.push({
131
+ name: 'get_entity',
132
+ title: 'Get registry entity dossier',
133
+ description: 'Fetch one registry record. format "markdown" (default) returns a token-efficient dossier: title, canonical URL, official source verification link, key fields table, recent change triggers and the non-FCRA disclaimer. format "json" returns structured fields. Free and CDN-cached; set live=true for the metered, uncached /api/v1 lookup (API key or x402). Data is republished from public government registries: not a consumer report under the FCRA; verify with the primary source.',
134
+ inputSchema: {
135
+ type: 'object',
136
+ properties: {
137
+ market: marketProp,
138
+ id: { type: 'string', minLength: 1, maxLength: 128, description: idParam?.description ?? 'Registry id (USDOT, N-number, CIK, NPI, OSHA activity number, USAspending award id, ...)' },
139
+ format: { type: 'string', enum: ['markdown', 'json'], default: 'markdown', description: 'markdown (fewest tokens) or json' },
140
+ live: { type: 'boolean', default: false, description: 'Use the paid, uncached API (JSON only). Requires REGISTRYHOUND_API_KEY or x402 payment_signature.' },
141
+ ...PAYMENT_PROPS,
142
+ },
143
+ required: ['market', 'id'],
144
+ additionalProperties: false,
145
+ },
146
+ annotations: { title: 'Get registry entity dossier', ...READ_ONLY },
147
+ run: async (a) => {
148
+ const vals = { market: String(a.market ?? ''), id: String(a.id ?? '').trim() };
149
+ if (a.live) {
150
+ const path = paidEntity?.path ?? '/api/v1/{market}/entity/{id}';
151
+ return paidResult(s, await call(s, server + fill(path, vals), { auth: true, paymentSignature: a.payment_signature, idempotencyKey: a.idempotency_key }, fetchImpl));
152
+ }
153
+ const md = a.format !== 'json';
154
+ const path = md ? (mdOp?.path ?? '/{market}/entity/{id}.md') : (jsonOp?.path ?? '/{market}/entity/{id}.json');
155
+ return freeResult(await call(s, server + fill(path, vals), { accept: md ? 'text/markdown' : 'application/json' }, fetchImpl));
156
+ },
157
+ });
158
+ // --- get_triggers (paid) ---
159
+ const trigOp = byId(spec, 'listTriggers');
160
+ const trigParams = params(spec, trigOp, 'query').filter(p => p.name !== 'format');
161
+ const trigProps = trigParams.length
162
+ ? Object.fromEntries(trigParams.map(p => [p.name, paramProp(spec, p)]))
163
+ : { since: { type: 'string' }, until: { type: 'string' }, type: { type: 'string' }, state: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'integer' } };
164
+ const price = trigOp?.op['x-x402']?.priceUsd;
165
+ tools.push({
166
+ name: 'get_triggers',
167
+ title: 'Get change-detection triggers',
168
+ description: `Page through change-detection triggers for one registry (new registrations, ownership transfers, status changes, filings, penalties, award changes), newest cursor last. Paid: uses REGISTRYHOUND_API_KEY, or returns an x402 payment offer${price ? ` ($${price} USDC per page)` : ''} when no key is set. Pass next_cursor back as cursor for the next page.`,
169
+ inputSchema: { type: 'object', properties: { market: marketProp, ...trigProps, ...PAYMENT_PROPS }, required: ['market'], additionalProperties: false },
170
+ annotations: { title: 'Get change-detection triggers', ...READ_ONLY, idempotentHint: false },
171
+ run: async (a) => {
172
+ const path = fill(trigOp?.path ?? '/api/v1/{market}/triggers', { market: String(a.market ?? '') });
173
+ return paidResult(s, await call(s, `${server}${path}${qs(a, Object.keys(trigProps))}`, { auth: true, paymentSignature: a.payment_signature, idempotencyKey: a.idempotency_key }, fetchImpl));
174
+ },
175
+ });
176
+ // --- resolve_entity (paid; Full API plan or x402) ---
177
+ const resolveOp = byId(spec, 'resolveEntity') ?? operations(spec).find(o => o.method === 'get' && /\/resolve$/.test(o.path));
178
+ const resolveParams = params(spec, resolveOp, 'query');
179
+ const resolveProps = resolveParams.length
180
+ ? Object.fromEntries(resolveParams.map(p => [p.name, paramProp(spec, p)]))
181
+ : {
182
+ q: { type: 'string', description: 'Company or entity name' },
183
+ ein: { type: 'string' }, uei: { type: 'string', description: 'SAM.gov UEI' }, cik: { type: 'string', description: 'SEC CIK' },
184
+ usdot: { type: 'string', description: 'FMCSA USDOT number' }, frn: { type: 'string', description: 'FCC Registration Number' },
185
+ state: { type: 'string', description: '2-letter state' }, markets: { type: 'string', description: `Comma list of registries (${markets.join(',')})` },
186
+ };
187
+ const rPrice = resolveOp?.op['x-x402']?.priceUsd;
188
+ tools.push({
189
+ name: 'resolve_entity',
190
+ title: 'Resolve an entity across registries',
191
+ description: `Link one company across every registry: exact identifier matches (UEI, CIK, USDOT, FRN, ...) first, then normalized legal name + state. Returns matched records grouped by registry with canonical links and recent trigger counts. Paid: Full API plan key, or an x402 offer${rPrice ? ` ($${rPrice} USDC)` : ''} when no key is set. Give at least q or one identifier.`,
192
+ inputSchema: { type: 'object', properties: { ...resolveProps, ...PAYMENT_PROPS }, additionalProperties: false },
193
+ annotations: { title: 'Resolve an entity across registries', ...READ_ONLY },
194
+ run: async (a) => {
195
+ const path = resolveOp?.path ?? '/api/v1/resolve';
196
+ return paidResult(s, await call(s, `${server}${path}${qs(a, Object.keys(resolveProps))}`, { auth: true, paymentSignature: a.payment_signature, idempotencyKey: a.idempotency_key }, fetchImpl));
197
+ },
198
+ });
199
+ return tools;
200
+ }
201
+ /** Fetch the OpenAPI document; null on any failure (tools fall back to built-in schemas). */
202
+ export async function loadSpec(s, fetchImpl = fetch) {
203
+ try {
204
+ const r = await call(s, s.openapiUrl, {}, fetchImpl);
205
+ if (!r.ok)
206
+ return null;
207
+ const j = JSON.parse(r.body);
208
+ return j && typeof j === 'object' && j.paths ? j : null;
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ }
@@ -0,0 +1,10 @@
1
+ import { type Server } from 'node:http';
2
+ import type { RegistryHoundMcp } from './server.js';
3
+ export declare function runStdio(mcp: RegistryHoundMcp, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream): Promise<void>;
4
+ export interface HttpOptions {
5
+ host: string;
6
+ port: number;
7
+ token?: string;
8
+ allowedOrigins?: string[];
9
+ }
10
+ export declare function startHttp(mcp: RegistryHoundMcp, o: HttpOptions): Promise<Server>;
@@ -0,0 +1,116 @@
1
+ // stdio (newline-delimited JSON-RPC) and HTTP transports: legacy HTTP+SSE (GET /sse + POST /messages)
2
+ // and Streamable HTTP in JSON-response mode (POST /mcp). Only node: built-ins.
3
+ import { createServer } from 'node:http';
4
+ import { randomUUID } from 'node:crypto';
5
+ const PARSE_ERROR = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } };
6
+ export function runStdio(mcp, input = process.stdin, output = process.stdout) {
7
+ let buf = '';
8
+ const write = (m) => output.write(JSON.stringify(m) + '\n');
9
+ const pending = new Set();
10
+ const onLine = (line) => {
11
+ if (!line.trim())
12
+ return;
13
+ let msg;
14
+ try {
15
+ msg = JSON.parse(line);
16
+ }
17
+ catch {
18
+ write(PARSE_ERROR);
19
+ return;
20
+ }
21
+ const p = mcp.handle(msg).then(r => { if (r)
22
+ write(r); }).finally(() => pending.delete(p));
23
+ pending.add(p);
24
+ };
25
+ input.setEncoding?.('utf8');
26
+ input.on('data', (chunk) => {
27
+ buf += chunk;
28
+ let i;
29
+ while ((i = buf.indexOf('\n')) >= 0) {
30
+ onLine(buf.slice(0, i).replace(/\r$/, ''));
31
+ buf = buf.slice(i + 1);
32
+ }
33
+ });
34
+ return new Promise(resolve => input.on('end', async () => { if (buf)
35
+ onLine(buf); await Promise.all(pending); resolve(); }));
36
+ }
37
+ const readBody = (req, max = 1_000_000) => new Promise((resolve, reject) => {
38
+ let size = 0;
39
+ const parts = [];
40
+ req.on('data', (c) => { size += c.length; if (size > max) {
41
+ reject(new Error('too large'));
42
+ req.destroy();
43
+ }
44
+ else
45
+ parts.push(c); });
46
+ req.on('end', () => resolve(Buffer.concat(parts).toString('utf8')));
47
+ req.on('error', reject);
48
+ });
49
+ export function startHttp(mcp, o) {
50
+ const sessions = new Map();
51
+ const local = (origin) => /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(origin);
52
+ const server = createServer(async (req, res) => {
53
+ const url = new URL(req.url ?? '/', 'http://local');
54
+ const json = (code, body) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
55
+ // DNS-rebinding guard: browsers send Origin; only localhost (or listed origins) may call.
56
+ const origin = req.headers.origin;
57
+ if (origin && !local(origin) && !(o.allowedOrigins ?? []).includes(origin))
58
+ return json(403, { error: 'origin_not_allowed' });
59
+ if (o.token && req.headers.authorization !== `Bearer ${o.token}`)
60
+ return json(401, { error: 'unauthorized' });
61
+ if (req.method === 'GET' && url.pathname === '/health')
62
+ return json(200, { ok: true });
63
+ // Legacy HTTP+SSE: the stream announces where to POST, responses come back as "message" events.
64
+ if (req.method === 'GET' && url.pathname === '/sse') {
65
+ const id = randomUUID();
66
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
67
+ res.write(`event: endpoint\ndata: /messages?sessionId=${id}\n\n`);
68
+ sessions.set(id, res);
69
+ const ka = setInterval(() => res.write(': keep-alive\n\n'), 25_000);
70
+ req.on('close', () => { clearInterval(ka); sessions.delete(id); });
71
+ return;
72
+ }
73
+ if (req.method === 'POST' && url.pathname === '/messages') {
74
+ const stream = sessions.get(url.searchParams.get('sessionId') ?? '');
75
+ if (!stream)
76
+ return json(404, { error: 'unknown_session' });
77
+ let msg;
78
+ try {
79
+ msg = JSON.parse(await readBody(req));
80
+ }
81
+ catch {
82
+ return json(400, PARSE_ERROR);
83
+ }
84
+ res.writeHead(202).end('Accepted');
85
+ const out = await mcp.handle(msg);
86
+ if (out)
87
+ stream.write(`event: message\ndata: ${JSON.stringify(out)}\n\n`);
88
+ return;
89
+ }
90
+ // Streamable HTTP (stateless, JSON responses).
91
+ if (url.pathname === '/mcp') {
92
+ if (req.method !== 'POST') {
93
+ res.writeHead(405, { allow: 'POST' }).end();
94
+ return;
95
+ }
96
+ let msg;
97
+ try {
98
+ msg = JSON.parse(await readBody(req));
99
+ }
100
+ catch {
101
+ return json(400, PARSE_ERROR);
102
+ }
103
+ const out = await mcp.handle(msg);
104
+ if (!out) {
105
+ res.writeHead(202).end();
106
+ return;
107
+ }
108
+ return json(200, out);
109
+ }
110
+ json(404, { error: 'not_found', endpoints: ['GET /sse', 'POST /messages?sessionId=', 'POST /mcp', 'GET /health'] });
111
+ });
112
+ return new Promise((resolve, reject) => {
113
+ server.once('error', reject);
114
+ server.listen(o.port, o.host, () => resolve(server));
115
+ });
116
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
- {
2
- "name": "@registryhound/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@registryhound/mcp",
3
+ "version": "0.1.1",
4
+ "mcpName": "io.github.Baffles78/registryhound",
5
+ "description": "Official RegistryHound MCP server: search U.S. public registries (FMCSA, FAA, SEC, CMS NPPES, OSHA, USAspending and more), read entity dossiers, change-detection triggers and cross-registry resolution. Zero dependencies.",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "author": "Opimus LLC",
9
+ "homepage": "https://registryhound.com/docs",
10
+ "repository": { "type": "git", "url": "git+https://github.com/Baffles78/registryhound-mcp.git" },
11
+ "keywords": ["mcp", "model-context-protocol", "registryhound", "fmcsa", "faa", "sec", "edgar", "npi", "osha", "usaspending", "public-records", "x402", "change-detection"],
12
+ "bin": { "registryhound-mcp": "dist/cli.js" },
13
+ "main": "dist/index.js",
14
+ "types": "dist/index.d.ts",
15
+ "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } },
16
+ "files": ["dist", "README.md", "LICENSE"],
17
+ "engines": { "node": ">=18" },
18
+ "publishConfig": { "access": "public" },
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.json && node -e \"require('fs').chmodSync('dist/cli.js',0o755)\"",
21
+ "test": "node --test test/*.test.mjs",
22
+ "prepublishOnly": "npm run build && npm test"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^22.20.7",
26
+ "typescript": "^7.0.2"
27
+ }
28
+ }