openrich 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/.env.example +23 -0
- package/LICENSE +21 -0
- package/README.md +410 -2
- package/assets/logo.svg +41 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +144 -0
- package/dist/env.d.ts +5 -0
- package/dist/env.js +24 -0
- package/dist/eval.d.ts +30 -0
- package/dist/eval.js +78 -0
- package/dist/mcp/client.d.ts +31 -0
- package/dist/mcp/client.js +94 -0
- package/dist/mcp/oauth.d.ts +13 -0
- package/dist/mcp/oauth.js +93 -0
- package/dist/mcp/server.d.ts +87 -0
- package/dist/mcp/server.js +125 -0
- package/dist/merge.d.ts +7 -0
- package/dist/merge.js +39 -0
- package/dist/providers/devplatforms.d.ts +34 -0
- package/dist/providers/devplatforms.js +612 -0
- package/dist/providers/finders.d.ts +38 -0
- package/dist/providers/finders.js +708 -0
- package/dist/providers/freetier.d.ts +9 -0
- package/dist/providers/freetier.js +254 -0
- package/dist/providers/github.d.ts +8 -0
- package/dist/providers/github.js +109 -0
- package/dist/providers/identity.d.ts +5 -0
- package/dist/providers/identity.js +62 -0
- package/dist/providers/index.d.ts +10 -0
- package/dist/providers/index.js +68 -0
- package/dist/providers/knowledge.d.ts +52 -0
- package/dist/providers/knowledge.js +302 -0
- package/dist/providers/pattern.d.ts +6 -0
- package/dist/providers/pattern.js +99 -0
- package/dist/providers/registries.d.ts +36 -0
- package/dist/providers/registries.js +396 -0
- package/dist/providers/research.d.ts +30 -0
- package/dist/providers/research.js +471 -0
- package/dist/providers/signals.d.ts +15 -0
- package/dist/providers/signals.js +116 -0
- package/dist/providers/smtp.d.ts +25 -0
- package/dist/providers/smtp.js +97 -0
- package/dist/providers/social.d.ts +37 -0
- package/dist/providers/social.js +657 -0
- package/dist/providers/verifiers.d.ts +47 -0
- package/dist/providers/verifiers.js +455 -0
- package/dist/providers/websearch.d.ts +32 -0
- package/dist/providers/websearch.js +346 -0
- package/dist/router.d.ts +31 -0
- package/dist/router.js +214 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +52 -0
- package/dist/store.d.ts +32 -0
- package/dist/store.js +95 -0
- package/dist/types.d.ts +82 -0
- package/dist/types.js +1 -0
- package/dist/util/http.d.ts +19 -0
- package/dist/util/http.js +34 -0
- package/dist/util/match.d.ts +23 -0
- package/dist/util/match.js +72 -0
- package/dist/util/names.d.ts +11 -0
- package/dist/util/names.js +56 -0
- package/dist/util/patterns.d.ts +14 -0
- package/dist/util/patterns.js +61 -0
- package/package.json +55 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env -S node --disable-warning=ExperimentalWarning
|
|
2
|
+
import { envFileForWrite } from "./env.js";
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { enrich, isEnabled } from "./router.js";
|
|
6
|
+
import { evaluate } from "./eval.js";
|
|
7
|
+
import { serve } from "./server.js";
|
|
8
|
+
import { DEFAULT_PROVIDERS } from "./providers/index.js";
|
|
9
|
+
import { Store } from "./store.js";
|
|
10
|
+
import { mcpLogin } from "./mcp/oauth.js";
|
|
11
|
+
import { McpClient } from "./mcp/client.js";
|
|
12
|
+
import { serveStdio } from "./mcp/server.js";
|
|
13
|
+
import { chmodSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { dirname } from 'node:path';
|
|
15
|
+
/** Providers whose free plan works only through their MCP server: sign in once, token goes to .env. */
|
|
16
|
+
const MCP_LOGINS = {
|
|
17
|
+
enrow: { url: 'https://mcp.enrow.io/mcp', env: 'ENROW_MCP_TOKEN' },
|
|
18
|
+
};
|
|
19
|
+
const HELP = `openrich: free-first people enrichment (one waterfall over 80+ free sources)
|
|
20
|
+
|
|
21
|
+
openrich person --name "Jane Doe" --domain acme.com [--company Acme] [--email x@y] [--github login]
|
|
22
|
+
[--free-only] [--fresh] [--only github,pattern] [--json] [--verbose]
|
|
23
|
+
openrich eval people.csv [--free-only] [--json] # CSV columns: name, domain|company, email
|
|
24
|
+
openrich providers # what is enabled, quota left
|
|
25
|
+
openrich serve [--port 8787] # HTTP API on localhost (POST /enrich, POST /mcp)
|
|
26
|
+
openrich mcp # MCP server on stdio, for AI agents
|
|
27
|
+
openrich login enrow # sign in to a provider's MCP server (free plan via MCP)
|
|
28
|
+
openrich mcp-tools enrow # list that MCP server's tools
|
|
29
|
+
|
|
30
|
+
Keys (optional, your own free-plan accounts) go in ~/.openrich/.env (or ./.env), KEY=value per line:
|
|
31
|
+
GITHUB_TOKEN HUNTER_API_KEY PDL_API_KEY ENROW_API_KEY GETPROSPECT_API_KEY GRAVATAR_API_KEY
|
|
32
|
+
REACHER_URL (self-hosted Reacher, needs a server with outbound port 25)
|
|
33
|
+
`;
|
|
34
|
+
function printResult(r, verbose) {
|
|
35
|
+
const rows = Object.entries(r.best).map(([f, v]) => [f, v.value, v.confidence.toFixed(2), v.sources.join('+')]);
|
|
36
|
+
const w = [0, 1, 2].map((i) => Math.max(...rows.map((x) => x[i].length), 6));
|
|
37
|
+
console.log(`\n${r.query.name ?? r.query.email ?? r.query.github}${r.query.domain ? ` @ ${r.query.domain}` : ''}`);
|
|
38
|
+
for (const x of rows)
|
|
39
|
+
console.log(` ${x[0].padEnd(w[0])} ${x[1].padEnd(w[1])} ${x[2].padEnd(w[2])} ${x[3]}`);
|
|
40
|
+
if (verbose) {
|
|
41
|
+
for (const [f, alts] of Object.entries(r.alternatives))
|
|
42
|
+
for (const a of alts)
|
|
43
|
+
console.log(` (alt ${f}) ${a.value} ${a.confidence.toFixed(2)} ${a.sources.join('+')}`);
|
|
44
|
+
}
|
|
45
|
+
console.log('\n trace: ' + r.trace.map((t) => `${t.provider}:${t.status}${t.ms ? `(${t.ms}ms)` : ''}`).join(' '));
|
|
46
|
+
if (verbose)
|
|
47
|
+
for (const t of r.trace)
|
|
48
|
+
if (t.note)
|
|
49
|
+
console.log(` ${t.provider}: ${t.note}`);
|
|
50
|
+
}
|
|
51
|
+
async function main() {
|
|
52
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
53
|
+
if (cmd === '--version' || cmd === '-V' || cmd === 'version') {
|
|
54
|
+
console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const { values, positionals } = parseArgs({
|
|
58
|
+
args: rest,
|
|
59
|
+
allowPositionals: true,
|
|
60
|
+
options: {
|
|
61
|
+
name: { type: 'string' }, domain: { type: 'string' }, company: { type: 'string' },
|
|
62
|
+
email: { type: 'string' }, github: { type: 'string' }, only: { type: 'string' },
|
|
63
|
+
'free-only': { type: 'boolean' }, fresh: { type: 'boolean' }, json: { type: 'boolean' },
|
|
64
|
+
verbose: { type: 'boolean', short: 'v' }, port: { type: 'string' },
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
const opts = {
|
|
68
|
+
freeTier: !values['free-only'],
|
|
69
|
+
fresh: values.fresh,
|
|
70
|
+
only: values.only?.split(','),
|
|
71
|
+
log: values.verbose ? (m) => console.error(` · ${m}`) : undefined,
|
|
72
|
+
};
|
|
73
|
+
if (cmd === 'person') {
|
|
74
|
+
const r = await enrich({ name: values.name, domain: values.domain, company: values.company, email: values.email, github: values.github }, opts);
|
|
75
|
+
if (values.json)
|
|
76
|
+
console.log(JSON.stringify(r, null, 2));
|
|
77
|
+
else
|
|
78
|
+
printResult(r, Boolean(values.verbose));
|
|
79
|
+
}
|
|
80
|
+
else if (cmd === 'eval') {
|
|
81
|
+
if (!positionals[0])
|
|
82
|
+
throw new Error('usage: enrich eval people.csv');
|
|
83
|
+
const rep = await evaluate(positionals[0], opts);
|
|
84
|
+
if (values.json)
|
|
85
|
+
return console.log(JSON.stringify(rep, null, 2));
|
|
86
|
+
const pct = (n) => `${((100 * n) / Math.max(rep.people, 1)).toFixed(0)}%`;
|
|
87
|
+
console.log(`people: ${rep.people}`);
|
|
88
|
+
console.log(`email found (>= threshold): ${rep.emailFound} (${pct(rep.emailFound)})`);
|
|
89
|
+
console.log(`email correct: ${rep.emailCorrect} (${pct(rep.emailCorrect)}), wrong: ${rep.emailWrong}`);
|
|
90
|
+
console.log(`free-tier API calls: ${rep.freeTierCalls}`);
|
|
91
|
+
console.log('per source (returned / correct):');
|
|
92
|
+
for (const [s, v] of Object.entries(rep.sources).sort((a, b) => b[1].correct - a[1].correct))
|
|
93
|
+
console.log(` ${s.padEnd(12)} ${v.returned} / ${v.correct}`);
|
|
94
|
+
for (const r of rep.rows)
|
|
95
|
+
console.log(` ${r.correct ? 'OK ' : '-- '} ${r.name.padEnd(24)} ${String(r.got).padEnd(36)} ${r.confidence.toFixed(2)} ${r.sources.join('+')}`);
|
|
96
|
+
}
|
|
97
|
+
else if (cmd === 'providers') {
|
|
98
|
+
const store = new Store();
|
|
99
|
+
for (const p of DEFAULT_PROVIDERS) {
|
|
100
|
+
const on = isEnabled(p, process.env);
|
|
101
|
+
const q = p.quota ? `${store.quotaLeft(p.id, p.quota)}/${p.quota.limit} per ${p.quota.period}` : 'no quota';
|
|
102
|
+
console.log(`${on ? 'on ' : 'off'} ${p.id.padEnd(12)} ${p.kind.padEnd(9)} ${q.padEnd(18)} ${p.description}${on ? '' : ` [set ${p.id === 'enrow' ? 'ENROW_API_KEY or run: openrich login enrow' : p.keyEnv}]`}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
else if (cmd === 'login') {
|
|
106
|
+
const m = MCP_LOGINS[positionals[0] ?? ''];
|
|
107
|
+
if (!m)
|
|
108
|
+
throw new Error(`usage: openrich login ${Object.keys(MCP_LOGINS).join('|')}`);
|
|
109
|
+
const { accessToken, expiresIn } = await mcpLogin(m.url, {
|
|
110
|
+
onUrl: (u) => console.log(`Open this link and sign in with your own account:\n\n${u}\n\nWaiting for the sign-in...`),
|
|
111
|
+
});
|
|
112
|
+
const file = envFileForWrite();
|
|
113
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
114
|
+
const lines = existsSync(file) ? readFileSync(file, 'utf8').split('\n').filter((l) => !l.startsWith(`${m.env}=`)) : [];
|
|
115
|
+
lines.push(`${m.env}=${accessToken}`);
|
|
116
|
+
writeFileSync(file, lines.filter((l, i) => l || i < lines.length - 1).join('\n') + '\n');
|
|
117
|
+
chmodSync(file, 0o600);
|
|
118
|
+
console.log(`Saved ${m.env} to ${file}${expiresIn ? ` (expires in ${Math.round(expiresIn / 86400)} days)` : ''}.`);
|
|
119
|
+
}
|
|
120
|
+
else if (cmd === 'mcp-tools') {
|
|
121
|
+
const m = MCP_LOGINS[positionals[0] ?? ''];
|
|
122
|
+
if (!m || !process.env[m.env])
|
|
123
|
+
throw new Error('usage: openrich mcp-tools <provider> (run openrich login <provider> first)');
|
|
124
|
+
const tools = await new McpClient(m.url, process.env[m.env]).listTools();
|
|
125
|
+
console.log(values.json ? JSON.stringify(tools, null, 2) : tools.map((t) => `${t.name}: ${(t.description ?? '').split('\n')[0]}`).join('\n'));
|
|
126
|
+
}
|
|
127
|
+
else if (cmd === 'mcp') {
|
|
128
|
+
serveStdio();
|
|
129
|
+
}
|
|
130
|
+
else if (cmd === 'serve') {
|
|
131
|
+
serve(Number(values.port ?? 8787));
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
console.log(HELP);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
main().then(() => {
|
|
138
|
+
// Exit as soon as the answer is printed; otherwise open keep-alive connections hold the process for seconds.
|
|
139
|
+
if (!['serve', 'mcp'].includes(process.argv[2]))
|
|
140
|
+
process.exit(0);
|
|
141
|
+
}).catch((e) => {
|
|
142
|
+
console.error(`error: ${e.message}`);
|
|
143
|
+
process.exit(1);
|
|
144
|
+
});
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Where an installed openrich keeps its keys (.env) and cache (db.sqlite). */
|
|
2
|
+
export declare const CONFIG_DIR: string;
|
|
3
|
+
export declare const HOME_ENV: string;
|
|
4
|
+
/** Where `openrich login` saves a token: ./.env when this folder has one (a clone), else ~/.openrich/.env. */
|
|
5
|
+
export declare function envFileForWrite(): string;
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
/** Where an installed openrich keeps its keys (.env) and cache (db.sqlite). */
|
|
5
|
+
export const CONFIG_DIR = process.env.OPENRICH_HOME ?? join(homedir(), '.openrich');
|
|
6
|
+
export const HOME_ENV = join(CONFIG_DIR, '.env');
|
|
7
|
+
/**
|
|
8
|
+
* Load KEY=value lines from ./.env (a project folder) and then ~/.openrich/.env (an installed CLI),
|
|
9
|
+
* never overriding real environment variables or an earlier file. Imported first by the CLI so every
|
|
10
|
+
* module (e.g. the User-Agent in util/http.ts) sees the values.
|
|
11
|
+
*/
|
|
12
|
+
for (const file of ['.env', HOME_ENV]) {
|
|
13
|
+
if (!existsSync(file))
|
|
14
|
+
continue;
|
|
15
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
16
|
+
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
17
|
+
if (m && !process.env[m[1]])
|
|
18
|
+
process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Where `openrich login` saves a token: ./.env when this folder has one (a clone), else ~/.openrich/.env. */
|
|
22
|
+
export function envFileForWrite() {
|
|
23
|
+
return existsSync('.env') ? '.env' : HOME_ENV;
|
|
24
|
+
}
|
package/dist/eval.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type RouterOptions } from './router.ts';
|
|
2
|
+
/** Minimal CSV parser (quoted fields, commas, newlines in quotes). */
|
|
3
|
+
export declare function parseCsv(text: string): Record<string, string>[];
|
|
4
|
+
export interface EvalReport {
|
|
5
|
+
people: number;
|
|
6
|
+
emailFound: number;
|
|
7
|
+
emailCorrect: number;
|
|
8
|
+
emailWrong: number;
|
|
9
|
+
/** Per source: how often it returned an email, and how often that email was right. */
|
|
10
|
+
sources: Record<string, {
|
|
11
|
+
returned: number;
|
|
12
|
+
correct: number;
|
|
13
|
+
}>;
|
|
14
|
+
freeTierCalls: number;
|
|
15
|
+
rows: {
|
|
16
|
+
name: string;
|
|
17
|
+
expected: string;
|
|
18
|
+
got: string | null;
|
|
19
|
+
confidence: number;
|
|
20
|
+
correct: boolean;
|
|
21
|
+
sources: string[];
|
|
22
|
+
}[];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Score the router against people whose email you already know.
|
|
26
|
+
* CSV columns: name, domain (or company), email. The known email is never sent to providers.
|
|
27
|
+
*/
|
|
28
|
+
export declare function evaluate(csvPath: string, opts?: RouterOptions & {
|
|
29
|
+
threshold?: number;
|
|
30
|
+
}): Promise<EvalReport>;
|
package/dist/eval.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { enrich } from "./router.js";
|
|
3
|
+
/** Minimal CSV parser (quoted fields, commas, newlines in quotes). */
|
|
4
|
+
export function parseCsv(text) {
|
|
5
|
+
const rows = [];
|
|
6
|
+
let row = [];
|
|
7
|
+
let cell = '';
|
|
8
|
+
let quoted = false;
|
|
9
|
+
for (let i = 0; i < text.length; i++) {
|
|
10
|
+
const ch = text[i];
|
|
11
|
+
if (quoted) {
|
|
12
|
+
if (ch === '"' && text[i + 1] === '"') {
|
|
13
|
+
cell += '"';
|
|
14
|
+
i++;
|
|
15
|
+
}
|
|
16
|
+
else if (ch === '"')
|
|
17
|
+
quoted = false;
|
|
18
|
+
else
|
|
19
|
+
cell += ch;
|
|
20
|
+
}
|
|
21
|
+
else if (ch === '"')
|
|
22
|
+
quoted = true;
|
|
23
|
+
else if (ch === ',') {
|
|
24
|
+
row.push(cell);
|
|
25
|
+
cell = '';
|
|
26
|
+
}
|
|
27
|
+
else if (ch === '\n' || ch === '\r') {
|
|
28
|
+
if (ch === '\r' && text[i + 1] === '\n')
|
|
29
|
+
i++;
|
|
30
|
+
row.push(cell);
|
|
31
|
+
cell = '';
|
|
32
|
+
if (row.some((c) => c.trim()))
|
|
33
|
+
rows.push(row);
|
|
34
|
+
row = [];
|
|
35
|
+
}
|
|
36
|
+
else
|
|
37
|
+
cell += ch;
|
|
38
|
+
}
|
|
39
|
+
row.push(cell);
|
|
40
|
+
if (row.some((c) => c.trim()))
|
|
41
|
+
rows.push(row);
|
|
42
|
+
const [head, ...body] = rows;
|
|
43
|
+
const keys = head.map((h) => h.trim().toLowerCase());
|
|
44
|
+
return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()])));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Score the router against people whose email you already know.
|
|
48
|
+
* CSV columns: name, domain (or company), email. The known email is never sent to providers.
|
|
49
|
+
*/
|
|
50
|
+
export async function evaluate(csvPath, opts = {}) {
|
|
51
|
+
const people = parseCsv(readFileSync(csvPath, 'utf8'));
|
|
52
|
+
const threshold = opts.threshold ?? 0.8;
|
|
53
|
+
const rep = { people: people.length, emailFound: 0, emailCorrect: 0, emailWrong: 0, sources: {}, freeTierCalls: 0, rows: [] };
|
|
54
|
+
for (const p of people) {
|
|
55
|
+
const expected = (p.email ?? '').toLowerCase();
|
|
56
|
+
const res = await enrich({ name: p.name, domain: p.domain || undefined, company: p.company || undefined }, opts);
|
|
57
|
+
rep.freeTierCalls += res.trace.filter((t) => ['hunter', 'pdl', 'enrow', 'getprospect', 'prospeo'].includes(t.provider) && (t.status === 'hit' || t.status === 'miss')).length;
|
|
58
|
+
const all = [res.best.email, ...(res.alternatives.email ?? [])].filter(Boolean);
|
|
59
|
+
for (const e of all)
|
|
60
|
+
for (const s of e.sources) {
|
|
61
|
+
const r = (rep.sources[s] ??= { returned: 0, correct: 0 });
|
|
62
|
+
r.returned++;
|
|
63
|
+
if (e.value.toLowerCase() === expected)
|
|
64
|
+
r.correct++;
|
|
65
|
+
}
|
|
66
|
+
const best = res.best.email;
|
|
67
|
+
const found = Boolean(best && best.confidence >= threshold);
|
|
68
|
+
const correct = found && best.value.toLowerCase() === expected;
|
|
69
|
+
if (found)
|
|
70
|
+
rep.emailFound++;
|
|
71
|
+
if (correct)
|
|
72
|
+
rep.emailCorrect++;
|
|
73
|
+
if (found && !correct)
|
|
74
|
+
rep.emailWrong++;
|
|
75
|
+
rep.rows.push({ name: p.name, expected, got: best?.value ?? null, confidence: best?.confidence ?? 0, correct, sources: best?.sources ?? [] });
|
|
76
|
+
}
|
|
77
|
+
return rep;
|
|
78
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal MCP client over Streamable HTTP (JSON-RPC 2.0). Lets the router call a provider's
|
|
3
|
+
* MCP server like an API: initialize once, then tools/call. Handles JSON and SSE responses.
|
|
4
|
+
*/
|
|
5
|
+
export declare class McpError extends Error {
|
|
6
|
+
status: number;
|
|
7
|
+
constructor(status: number, message: string);
|
|
8
|
+
}
|
|
9
|
+
export declare class McpClient {
|
|
10
|
+
private sessionId;
|
|
11
|
+
private nextId;
|
|
12
|
+
private ready;
|
|
13
|
+
private url;
|
|
14
|
+
private token;
|
|
15
|
+
private f;
|
|
16
|
+
constructor(url: string, token: string, f?: typeof fetch);
|
|
17
|
+
private post;
|
|
18
|
+
private rpc;
|
|
19
|
+
init(): Promise<void>;
|
|
20
|
+
listTools(): Promise<{
|
|
21
|
+
name: string;
|
|
22
|
+
description?: string;
|
|
23
|
+
inputSchema?: any;
|
|
24
|
+
}[]>;
|
|
25
|
+
/** Calls a tool. Returns structuredContent if present, else the parsed JSON of the first text block, else the text. */
|
|
26
|
+
callTool(name: string, args: object, timeoutMs?: number): Promise<{
|
|
27
|
+
isError: boolean;
|
|
28
|
+
data: any;
|
|
29
|
+
text: string;
|
|
30
|
+
}>;
|
|
31
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal MCP client over Streamable HTTP (JSON-RPC 2.0). Lets the router call a provider's
|
|
3
|
+
* MCP server like an API: initialize once, then tools/call. Handles JSON and SSE responses.
|
|
4
|
+
*/
|
|
5
|
+
export class McpError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
constructor(status, message) { super(message); this.status = status; }
|
|
8
|
+
}
|
|
9
|
+
export class McpClient {
|
|
10
|
+
sessionId = null;
|
|
11
|
+
nextId = 1;
|
|
12
|
+
ready = null;
|
|
13
|
+
url;
|
|
14
|
+
token;
|
|
15
|
+
f;
|
|
16
|
+
constructor(url, token, f = fetch) {
|
|
17
|
+
this.url = url;
|
|
18
|
+
this.token = token;
|
|
19
|
+
this.f = f;
|
|
20
|
+
}
|
|
21
|
+
async post(body, timeoutMs = 120000) {
|
|
22
|
+
const headers = {
|
|
23
|
+
'content-type': 'application/json',
|
|
24
|
+
accept: 'application/json, text/event-stream',
|
|
25
|
+
'mcp-protocol-version': '2025-06-18',
|
|
26
|
+
};
|
|
27
|
+
if (this.token)
|
|
28
|
+
headers.authorization = `Bearer ${this.token}`; // empty token = keyless server
|
|
29
|
+
if (this.sessionId)
|
|
30
|
+
headers['mcp-session-id'] = this.sessionId;
|
|
31
|
+
const res = await this.f(this.url, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
|
|
32
|
+
const sid = res.headers.get('mcp-session-id');
|
|
33
|
+
if (sid)
|
|
34
|
+
this.sessionId = sid;
|
|
35
|
+
return res;
|
|
36
|
+
}
|
|
37
|
+
async rpc(method, params = {}, timeoutMs) {
|
|
38
|
+
const id = this.nextId++;
|
|
39
|
+
const res = await this.post({ jsonrpc: '2.0', id, method, params }, timeoutMs);
|
|
40
|
+
if (!res.ok)
|
|
41
|
+
throw new McpError(res.status, `${method}: HTTP ${res.status} ${(await res.text()).slice(0, 300)}`);
|
|
42
|
+
const msg = await readMessage(res, id);
|
|
43
|
+
if (msg.error)
|
|
44
|
+
throw new McpError(res.status, `${method}: ${msg.error.message ?? JSON.stringify(msg.error)}`);
|
|
45
|
+
return msg.result;
|
|
46
|
+
}
|
|
47
|
+
init() {
|
|
48
|
+
this.ready ??= (async () => {
|
|
49
|
+
await this.rpc('initialize', {
|
|
50
|
+
protocolVersion: '2025-06-18',
|
|
51
|
+
capabilities: {},
|
|
52
|
+
clientInfo: { name: 'openrich', version: '0.1.0' },
|
|
53
|
+
});
|
|
54
|
+
await this.post({ jsonrpc: '2.0', method: 'notifications/initialized' }).then((r) => r.body?.cancel());
|
|
55
|
+
})();
|
|
56
|
+
return this.ready;
|
|
57
|
+
}
|
|
58
|
+
async listTools() {
|
|
59
|
+
await this.init();
|
|
60
|
+
return (await this.rpc('tools/list')).tools ?? [];
|
|
61
|
+
}
|
|
62
|
+
/** Calls a tool. Returns structuredContent if present, else the parsed JSON of the first text block, else the text. */
|
|
63
|
+
async callTool(name, args, timeoutMs) {
|
|
64
|
+
await this.init();
|
|
65
|
+
const r = await this.rpc('tools/call', { name, arguments: args }, timeoutMs);
|
|
66
|
+
const text = (r.content ?? []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
|
|
67
|
+
let data = r.structuredContent;
|
|
68
|
+
if (data === undefined) {
|
|
69
|
+
try {
|
|
70
|
+
data = JSON.parse(text);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
data = text;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return { isError: Boolean(r.isError), data, text };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Reads the JSON-RPC response with this id from a JSON or text/event-stream body. */
|
|
80
|
+
async function readMessage(res, id) {
|
|
81
|
+
const type = res.headers.get('content-type') ?? '';
|
|
82
|
+
if (!type.includes('text/event-stream'))
|
|
83
|
+
return res.json();
|
|
84
|
+
const text = await res.text();
|
|
85
|
+
for (const event of text.split(/\r?\n\r?\n/)) {
|
|
86
|
+
const data = event.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trimStart()).join('\n');
|
|
87
|
+
if (!data)
|
|
88
|
+
continue;
|
|
89
|
+
const msg = JSON.parse(data);
|
|
90
|
+
if (msg.id === id)
|
|
91
|
+
return msg;
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`no response for request ${id} in event stream`);
|
|
94
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth 2.1 login for a remote MCP server (MCP authorization spec): discovery, dynamic client
|
|
3
|
+
* registration, PKCE S256, redirect to 127.0.0.1. You sign in with your own account in your browser;
|
|
4
|
+
* the access token comes back to this machine only.
|
|
5
|
+
*/
|
|
6
|
+
export declare function mcpLogin(mcpUrl: string, opts: {
|
|
7
|
+
onUrl: (url: string) => void;
|
|
8
|
+
clientName?: string;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
accessToken: string;
|
|
12
|
+
expiresIn?: number;
|
|
13
|
+
}>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
/**
|
|
4
|
+
* OAuth 2.1 login for a remote MCP server (MCP authorization spec): discovery, dynamic client
|
|
5
|
+
* registration, PKCE S256, redirect to 127.0.0.1. You sign in with your own account in your browser;
|
|
6
|
+
* the access token comes back to this machine only.
|
|
7
|
+
*/
|
|
8
|
+
export async function mcpLogin(mcpUrl, opts) {
|
|
9
|
+
const origin = new URL(mcpUrl).origin;
|
|
10
|
+
const prm = await (await fetch(`${origin}/.well-known/oauth-protected-resource`)).json();
|
|
11
|
+
const issuer = prm.authorization_servers[0];
|
|
12
|
+
const meta = await (await fetch(`${issuer.replace(/\/$/, '')}/.well-known/oauth-authorization-server`)).json();
|
|
13
|
+
const verifier = randomBytes(32).toString('base64url');
|
|
14
|
+
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
|
15
|
+
const state = randomBytes(16).toString('base64url');
|
|
16
|
+
// Local callback server on a free port.
|
|
17
|
+
let resolveCode;
|
|
18
|
+
let rejectCode;
|
|
19
|
+
const gotCode = new Promise((res, rej) => { resolveCode = res; rejectCode = rej; });
|
|
20
|
+
const server = createServer((req, res) => {
|
|
21
|
+
const u = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
22
|
+
if (u.pathname !== '/callback') {
|
|
23
|
+
res.writeHead(404).end();
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const err = u.searchParams.get('error');
|
|
27
|
+
if (err) {
|
|
28
|
+
res.end(`Sign-in failed: ${err}. You can close this tab.`);
|
|
29
|
+
rejectCode(new Error(`oauth: ${err}`));
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (u.searchParams.get('state') !== state) {
|
|
33
|
+
res.writeHead(400).end('state mismatch');
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
res.end('Signed in. You can close this tab and go back to the terminal.');
|
|
37
|
+
resolveCode(u.searchParams.get('code') ?? '');
|
|
38
|
+
});
|
|
39
|
+
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
|
40
|
+
const port = server.address().port;
|
|
41
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
42
|
+
try {
|
|
43
|
+
const reg = await fetch(meta.registration_endpoint, {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: { 'content-type': 'application/json' },
|
|
46
|
+
body: JSON.stringify({
|
|
47
|
+
client_name: opts.clientName ?? 'openrich',
|
|
48
|
+
redirect_uris: [redirectUri],
|
|
49
|
+
grant_types: ['authorization_code'],
|
|
50
|
+
response_types: ['code'],
|
|
51
|
+
token_endpoint_auth_method: 'none',
|
|
52
|
+
}),
|
|
53
|
+
});
|
|
54
|
+
if (!reg.ok)
|
|
55
|
+
throw new Error(`client registration: HTTP ${reg.status} ${await reg.text()}`);
|
|
56
|
+
const { client_id } = await reg.json();
|
|
57
|
+
const auth = new URL(meta.authorization_endpoint);
|
|
58
|
+
auth.search = new URLSearchParams({
|
|
59
|
+
response_type: 'code',
|
|
60
|
+
client_id,
|
|
61
|
+
redirect_uri: redirectUri,
|
|
62
|
+
code_challenge: challenge,
|
|
63
|
+
code_challenge_method: 'S256',
|
|
64
|
+
state,
|
|
65
|
+
resource: prm.resource ?? mcpUrl,
|
|
66
|
+
...(meta.scopes_supported?.length ? { scope: meta.scopes_supported.join(' ') } : {}),
|
|
67
|
+
}).toString();
|
|
68
|
+
opts.onUrl(auth.toString());
|
|
69
|
+
const code = await Promise.race([
|
|
70
|
+
gotCode,
|
|
71
|
+
new Promise((_, rej) => setTimeout(() => rej(new Error('login timed out')), opts.timeoutMs ?? 300000)),
|
|
72
|
+
]);
|
|
73
|
+
const tok = await fetch(meta.token_endpoint, {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
76
|
+
body: new URLSearchParams({
|
|
77
|
+
grant_type: 'authorization_code',
|
|
78
|
+
code,
|
|
79
|
+
redirect_uri: redirectUri,
|
|
80
|
+
client_id,
|
|
81
|
+
code_verifier: verifier,
|
|
82
|
+
resource: prm.resource ?? mcpUrl,
|
|
83
|
+
}),
|
|
84
|
+
});
|
|
85
|
+
if (!tok.ok)
|
|
86
|
+
throw new Error(`token exchange: HTTP ${tok.status} ${await tok.text()}`);
|
|
87
|
+
const t = await tok.json();
|
|
88
|
+
return { accessToken: t.access_token, expiresIn: t.expires_in };
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
server.close();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { Store } from '../store.ts';
|
|
2
|
+
import type { EnrichResult } from '../types.ts';
|
|
3
|
+
export declare const TOOLS: ({
|
|
4
|
+
name: string;
|
|
5
|
+
title: string;
|
|
6
|
+
description: string;
|
|
7
|
+
inputSchema: {
|
|
8
|
+
type: string;
|
|
9
|
+
properties: {
|
|
10
|
+
name: {
|
|
11
|
+
type: string;
|
|
12
|
+
description: string;
|
|
13
|
+
};
|
|
14
|
+
domain: {
|
|
15
|
+
type: string;
|
|
16
|
+
description: string;
|
|
17
|
+
};
|
|
18
|
+
company: {
|
|
19
|
+
type: string;
|
|
20
|
+
description: string;
|
|
21
|
+
};
|
|
22
|
+
email: {
|
|
23
|
+
type: string;
|
|
24
|
+
description: string;
|
|
25
|
+
};
|
|
26
|
+
github: {
|
|
27
|
+
type: string;
|
|
28
|
+
description: string;
|
|
29
|
+
};
|
|
30
|
+
free_only: {
|
|
31
|
+
type: string;
|
|
32
|
+
description: string;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
anyOf: {
|
|
36
|
+
required: string[];
|
|
37
|
+
}[];
|
|
38
|
+
};
|
|
39
|
+
annotations: {
|
|
40
|
+
readOnlyHint: boolean;
|
|
41
|
+
openWorldHint: boolean;
|
|
42
|
+
};
|
|
43
|
+
} | {
|
|
44
|
+
name: string;
|
|
45
|
+
title: string;
|
|
46
|
+
description: string;
|
|
47
|
+
inputSchema: {
|
|
48
|
+
type: string;
|
|
49
|
+
properties: {
|
|
50
|
+
name?: undefined;
|
|
51
|
+
domain?: undefined;
|
|
52
|
+
company?: undefined;
|
|
53
|
+
email?: undefined;
|
|
54
|
+
github?: undefined;
|
|
55
|
+
free_only?: undefined;
|
|
56
|
+
};
|
|
57
|
+
anyOf?: undefined;
|
|
58
|
+
};
|
|
59
|
+
annotations: {
|
|
60
|
+
readOnlyHint: boolean;
|
|
61
|
+
openWorldHint?: undefined;
|
|
62
|
+
};
|
|
63
|
+
})[];
|
|
64
|
+
/** The compact answer an agent needs: per field, the best value, its confidence and sources. */
|
|
65
|
+
export declare function summarize(r: EnrichResult): {
|
|
66
|
+
query: import("../types.ts").PersonQuery;
|
|
67
|
+
fields: Record<string, {
|
|
68
|
+
value: string;
|
|
69
|
+
confidence: number;
|
|
70
|
+
sources: string[];
|
|
71
|
+
}>;
|
|
72
|
+
sourcesCalled: number;
|
|
73
|
+
cached: boolean;
|
|
74
|
+
};
|
|
75
|
+
type Rpc = {
|
|
76
|
+
jsonrpc: '2.0';
|
|
77
|
+
id?: string | number | null;
|
|
78
|
+
method: string;
|
|
79
|
+
params?: any;
|
|
80
|
+
};
|
|
81
|
+
export declare function createHandler(opts?: {
|
|
82
|
+
store?: Store;
|
|
83
|
+
env?: Record<string, string | undefined>;
|
|
84
|
+
}): (msg: Rpc) => Promise<object | null>;
|
|
85
|
+
/** stdio transport: one JSON-RPC message per line on stdin, replies on stdout. Logs go to stderr only. */
|
|
86
|
+
export declare function serveStdio(): void;
|
|
87
|
+
export {};
|