@mcpapi/cli 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/README.md +13 -2
- package/mcpapi.js +177 -0
- package/package.json +34 -4
package/README.md
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mcpapi/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[MCPAPI](https://getmcpapi.com)'s three tools from a terminal: search the APIs in your workspace in plain words, read one operation's schema, and run it. An agent with a shell (Claude Code, Codex, a CI job) can use every API you've connected without carrying any tool definitions.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx @mcpapi/cli login # or: npm install -g @mcpapi/cli, then mcpapi login
|
|
7
|
+
mcpapi search "refund a charge"
|
|
8
|
+
mcpapi details stripe.PostRefunds
|
|
9
|
+
mcpapi run stripe.PostRefunds --args '{"charge":"ch_123"}'
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Sign in with `mcpapi login` (opens your browser; you pick a workspace), or set `MCPAPI_KEY` to a key from the dashboard's Connected Agents page. The key wins when both are there. Full reference: https://docs.mcpapi.one/reference/cli/
|
|
13
|
+
|
|
14
|
+
No dependencies; Node 20 or later. MIT licensed.
|
package/mcpapi.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// mcpapi: MCPAPI's three tools from a terminal. Docs: https://docs.mcpapi.one/reference/cli/
|
|
3
|
+
// No dependencies: Node's fetch, http, crypto and parseArgs. It sends the tools' names and arguments to
|
|
4
|
+
// /mcp and prints their replies as they are, so it carries no copy of the tools' schemas.
|
|
5
|
+
import { parseArgs } from 'node:util'
|
|
6
|
+
import { createServer } from 'node:http'
|
|
7
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
8
|
+
import { spawn } from 'node:child_process'
|
|
9
|
+
import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
const VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
|
|
14
|
+
const BASE = (process.env.MCPAPI_URL || 'https://mcpapi.one').replace(/\/+$/, '')
|
|
15
|
+
const DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'mcpapi')
|
|
16
|
+
const FILE = join(DIR, 'credentials.json')
|
|
17
|
+
const FORM = { 'content-type': 'application/x-www-form-urlencoded' }
|
|
18
|
+
|
|
19
|
+
const HELP = `mcpapi ${VERSION}: the APIs in your MCPAPI workspace, from a terminal.
|
|
20
|
+
|
|
21
|
+
mcpapi search <what you want to do> [--source <api>] [--limit <1-20>]
|
|
22
|
+
mcpapi details <id> [--field <argument>]
|
|
23
|
+
mcpapi run <id> [--args '<json>' | --args -] [--connection <name>] [--search-id <id>]
|
|
24
|
+
mcpapi login | logout | whoami
|
|
25
|
+
|
|
26
|
+
Sign in with \`mcpapi login\` (opens your browser), or set MCPAPI_KEY to a key from the
|
|
27
|
+
dashboard's Connected Agents page; the key wins when both are there. \`--args -\` reads the JSON
|
|
28
|
+
from stdin. Replies are the tools' JSON; the exit code is 1 when a tool answers an error.
|
|
29
|
+
Docs: https://docs.mcpapi.one/reference/cli/`
|
|
30
|
+
|
|
31
|
+
function fail(message) {
|
|
32
|
+
console.error(`mcpapi: ${message}`)
|
|
33
|
+
process.exit(1)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// --- Credentials: a login saved for one MCPAPI address, readable only by you ---
|
|
37
|
+
const load = () => { try { const c = JSON.parse(readFileSync(FILE, 'utf8')); return c.base === BASE ? c : null } catch { return null } }
|
|
38
|
+
function save(c) {
|
|
39
|
+
mkdirSync(DIR, { recursive: true, mode: 0o700 })
|
|
40
|
+
writeFileSync(FILE, JSON.stringify({ ...c, base: BASE }, null, 2), { mode: 0o600 })
|
|
41
|
+
}
|
|
42
|
+
const claims = (jwt) => JSON.parse(Buffer.from(jwt.split('.')[1] ?? '', 'base64url').toString())
|
|
43
|
+
|
|
44
|
+
// The bearer for /mcp: MCPAPI_KEY, else the saved login, refreshed a minute before it expires.
|
|
45
|
+
// ponytail: two runs refreshing at once both use the same refresh token; Supabase allows reuse for a few
|
|
46
|
+
// seconds, so this holds for parallel runs. A lock file if that ever logs people out.
|
|
47
|
+
async function bearer(force = false) {
|
|
48
|
+
if (process.env.MCPAPI_KEY) return process.env.MCPAPI_KEY
|
|
49
|
+
const c = load()
|
|
50
|
+
if (!c) fail('Not signed in. Run `mcpapi login`, or set MCPAPI_KEY to a key from the dashboard\'s Connected Agents page.')
|
|
51
|
+
if (!force && claims(c.access_token).exp * 1000 > Date.now() + 60_000) return c.access_token
|
|
52
|
+
const expired = 'Your sign-in has expired. Run `mcpapi login`.'
|
|
53
|
+
if (!c.refresh_token) fail(expired)
|
|
54
|
+
const res = await fetch(c.token_endpoint, { method: 'POST', headers: FORM, body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: c.refresh_token, client_id: c.client_id }) })
|
|
55
|
+
if (!res.ok) fail(expired)
|
|
56
|
+
const t = await res.json()
|
|
57
|
+
save({ ...c, access_token: t.access_token, refresh_token: t.refresh_token ?? c.refresh_token })
|
|
58
|
+
return t.access_token
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// --- The three tools, through /mcp ---
|
|
62
|
+
async function call(name, args) {
|
|
63
|
+
const send = (token) => fetch(`${BASE}/mcp`, {
|
|
64
|
+
method: 'POST',
|
|
65
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${token}`, 'user-agent': `mcpapi-cli/${VERSION}` },
|
|
66
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
|
|
67
|
+
})
|
|
68
|
+
let res = await send(await bearer())
|
|
69
|
+
if (res.status === 401 && !process.env.MCPAPI_KEY) res = await send(await bearer(true))
|
|
70
|
+
const text = await res.text()
|
|
71
|
+
if (res.status === 401) fail(process.env.MCPAPI_KEY ? 'MCPAPI_KEY was refused. Check the key on the Connected Agents page.' : 'Signed out (the connection may have been removed). Run `mcpapi login`.')
|
|
72
|
+
if (!res.ok) { let e; try { e = JSON.parse(text).error } catch { /* not JSON */ } fail(e ?? `HTTP ${res.status}`) }
|
|
73
|
+
// The reply is plain JSON or a one-message event stream.
|
|
74
|
+
const msg = JSON.parse(text.startsWith('{') ? text : (text.split('\n').filter((l) => l.startsWith('data:')).at(-1) ?? 'data:{}').slice(5))
|
|
75
|
+
if (msg.error) fail(msg.error.message ?? JSON.stringify(msg.error))
|
|
76
|
+
const out = msg.result?.content?.[0]?.text ?? ''
|
|
77
|
+
let shown = out
|
|
78
|
+
if (process.stdout.isTTY) try { shown = JSON.stringify(JSON.parse(out), null, 2) } catch { /* not JSON */ }
|
|
79
|
+
console.log(shown)
|
|
80
|
+
if (msg.result?.isError) process.exitCode = 1
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// --- Sign-in: OAuth 2.1 with PKCE, the browser handing the code back to a local port ---
|
|
84
|
+
function openBrowser(url) {
|
|
85
|
+
const [cmd, args] = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]]
|
|
86
|
+
spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function login() {
|
|
90
|
+
const meta = await (await fetch(`${BASE}/.well-known/oauth-authorization-server`)).json()
|
|
91
|
+
const verifier = randomBytes(32).toString('base64url')
|
|
92
|
+
const state = randomBytes(16).toString('base64url')
|
|
93
|
+
let done
|
|
94
|
+
const answer = new Promise((resolve) => { done = resolve })
|
|
95
|
+
const handle = (req, res) => {
|
|
96
|
+
const u = new URL(req.url ?? '/', 'http://localhost')
|
|
97
|
+
if (u.pathname !== '/callback' || u.searchParams.get('state') !== state) { res.writeHead(404).end(); return }
|
|
98
|
+
const ok = u.searchParams.has('code')
|
|
99
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(`<p style="font-family:system-ui">${ok ? 'Signed in to MCPAPI. You can close this tab.' : 'Sign-in did not finish. See the terminal.'}</p>`)
|
|
100
|
+
done(u.searchParams)
|
|
101
|
+
}
|
|
102
|
+
// localhost can resolve to either address; listen on both, on one free port.
|
|
103
|
+
const v4 = createServer(handle)
|
|
104
|
+
await new Promise((resolve, reject) => v4.once('error', reject).listen(0, '127.0.0.1', resolve))
|
|
105
|
+
const port = v4.address().port
|
|
106
|
+
const v6 = createServer(handle).on('error', () => {}).listen(port, '::1')
|
|
107
|
+
const redirect = `http://localhost:${port}/callback`
|
|
108
|
+
|
|
109
|
+
// ponytail: a new client per login, as Claude Code and Codex do; old ones stay on the Connected Agents page until removed there.
|
|
110
|
+
const reg = await fetch(meta.registration_endpoint, {
|
|
111
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
112
|
+
body: JSON.stringify({ client_name: 'MCPAPI CLI', redirect_uris: [redirect], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none' }),
|
|
113
|
+
})
|
|
114
|
+
if (!reg.ok) fail(`Could not register the CLI with the sign-in server: ${await reg.text()}`)
|
|
115
|
+
const { client_id } = await reg.json()
|
|
116
|
+
const url = `${meta.authorization_endpoint}?${new URLSearchParams({
|
|
117
|
+
response_type: 'code', client_id, redirect_uri: redirect, state, scope: 'openid email', resource: `${BASE}/mcp`,
|
|
118
|
+
code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256',
|
|
119
|
+
})}`
|
|
120
|
+
console.error(`Opening your browser to sign in and pick a workspace. If it doesn't open, visit:\n\n ${url}\n`)
|
|
121
|
+
openBrowser(url)
|
|
122
|
+
|
|
123
|
+
const timer = setTimeout(() => done(null), 5 * 60_000)
|
|
124
|
+
const params = await answer
|
|
125
|
+
clearTimeout(timer)
|
|
126
|
+
for (const s of [v4, v6]) { s.close(); s.closeAllConnections() }
|
|
127
|
+
if (!params) fail('Timed out waiting for the browser. Run `mcpapi login` again.')
|
|
128
|
+
if (!params.has('code')) fail(`Sign-in refused: ${params.get('error_description') ?? params.get('error') ?? 'no code'}`)
|
|
129
|
+
const tok = await fetch(meta.token_endpoint, {
|
|
130
|
+
method: 'POST', headers: FORM,
|
|
131
|
+
body: new URLSearchParams({ grant_type: 'authorization_code', code: params.get('code'), redirect_uri: redirect, client_id, code_verifier: verifier }),
|
|
132
|
+
})
|
|
133
|
+
if (!tok.ok) fail(`Sign-in failed: ${await tok.text()}`)
|
|
134
|
+
const t = await tok.json()
|
|
135
|
+
save({ client_id, token_endpoint: meta.token_endpoint, access_token: t.access_token, refresh_token: t.refresh_token })
|
|
136
|
+
console.error(`Signed in as ${claims(t.access_token).email ?? 'you'}.`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// --- Commands ---
|
|
140
|
+
let parsed
|
|
141
|
+
try {
|
|
142
|
+
parsed = parseArgs({
|
|
143
|
+
allowPositionals: true,
|
|
144
|
+
options: {
|
|
145
|
+
source: { type: 'string' }, limit: { type: 'string' }, field: { type: 'string' }, args: { type: 'string' },
|
|
146
|
+
connection: { type: 'string' }, 'search-id': { type: 'string' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
} catch (e) { fail(`${e.message}\n\n${HELP}`) }
|
|
150
|
+
const { values: o, positionals: [cmd, ...rest] } = parsed
|
|
151
|
+
|
|
152
|
+
if (o.version) console.log(VERSION)
|
|
153
|
+
else if (o.help || !cmd) console.log(HELP)
|
|
154
|
+
else if (cmd === 'search') {
|
|
155
|
+
if (!rest.length) fail('Say what you want to do, e.g. `mcpapi search "refund a charge"`.')
|
|
156
|
+
await call('search_tools', { query: rest.join(' '), ...(o.source ? { source: o.source } : {}), ...(o.limit ? { limit: Number(o.limit) } : {}) })
|
|
157
|
+
} else if (cmd === 'details') {
|
|
158
|
+
if (!rest[0]) fail('Give an id from `mcpapi search`, e.g. `mcpapi details stripe.PostRefunds`.')
|
|
159
|
+
await call('get_tool_details', { id: rest[0], ...(o.field ? { field: o.field } : {}) })
|
|
160
|
+
} else if (cmd === 'run') {
|
|
161
|
+
if (!rest[0]) fail('Give an id from `mcpapi search`, e.g. `mcpapi run stripe.GetBalance`.')
|
|
162
|
+
let args = {}
|
|
163
|
+
if (o.args !== undefined) {
|
|
164
|
+
try { args = JSON.parse(o.args === '-' ? readFileSync(0, 'utf8') : o.args) } catch { fail('--args must be JSON, e.g. --args \'{"limit":3}\'.') }
|
|
165
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) fail('--args must be a JSON object.')
|
|
166
|
+
}
|
|
167
|
+
await call('execute_tool', { id: rest[0], arguments: args, ...(o['search-id'] ? { search_id: o['search-id'] } : {}), ...(o.connection ? { connection: o.connection } : {}) })
|
|
168
|
+
} else if (cmd === 'login') await login()
|
|
169
|
+
else if (cmd === 'logout') {
|
|
170
|
+
rmSync(FILE, { force: true })
|
|
171
|
+
console.error('Signed out on this computer. The connection stays on the dashboard\'s Connected Agents page until you remove it there.')
|
|
172
|
+
} else if (cmd === 'whoami') {
|
|
173
|
+
const c = load()
|
|
174
|
+
if (process.env.MCPAPI_KEY) console.log(`Using the key in MCPAPI_KEY${c ? ' (your saved login is ignored while it is set)' : ''}, on ${BASE}.`)
|
|
175
|
+
else if (c) console.log(`Signed in as ${claims(c.access_token).email ?? 'unknown'}, on ${BASE}.`)
|
|
176
|
+
else console.log('Not signed in. Run `mcpapi login`, or set MCPAPI_KEY.')
|
|
177
|
+
} else fail(`Unknown command "${cmd}".\n\n${HELP}`)
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcpapi/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "MCPAPI's three tools from a terminal: search your APIs, read one operation, run it.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"mcpapi": "mcpapi.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"mcpapi.js"
|
|
11
|
+
],
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=20"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node mcpapi.js --version && node mcpapi.js --help"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://docs.mcpapi.one/reference/cli/",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/cucoleadan/mcpapi-server.git",
|
|
22
|
+
"directory": "cli"
|
|
23
|
+
},
|
|
24
|
+
"bugs": "https://github.com/cucoleadan/mcpapi-server/issues",
|
|
25
|
+
"keywords": [
|
|
26
|
+
"mcp",
|
|
27
|
+
"mcpapi",
|
|
28
|
+
"openapi",
|
|
29
|
+
"cli",
|
|
30
|
+
"agents"
|
|
31
|
+
],
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
}
|
|
36
|
+
}
|