@maviapi/mcp 0.0.0-stage → 0.1.0
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 +21 -0
- package/README.md +116 -2
- package/dist/catalog.js +298 -0
- package/dist/client.js +113 -0
- package/dist/config.js +40 -0
- package/dist/index.js +11 -0
- package/dist/server.js +21 -0
- package/dist/tools.js +425 -0
- package/package.json +59 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KuzenLabs
|
|
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,117 @@
|
|
|
1
|
-
#
|
|
1
|
+
# maviapi MCP server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Give Claude, Cursor, or any MCP client **live, structured JSON from websites that have no API**: Booking.com, Airbnb, Tripadvisor, Kiwi.com, Trainline, Hepsiburada, Yemeksepeti and more, plus any site you ask for.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
You: Find me a 3-night Airbnb in Lisbon next month under €120 a night.
|
|
7
|
+
Claude: → search_apis "airbnb" → get_api "airbnb" → call_api airbnb/search {location: "Lisbon", …}
|
|
8
|
+
Here are the 5 best-rated options under €120…
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Agents are bad at the web. Browsing is slow, burns tokens on raw HTML, and stalls on bot protection; hand-written scrapers break the next time the site changes its layout. [maviapi](https://maviapi.com) turns a website into a hosted, schema-first JSON API, and **monitors and repairs it when the site changes**, so the endpoint your agent depends on keeps answering. This server puts those APIs one tool call away.
|
|
12
|
+
|
|
13
|
+
**Works with no setup.** Out of the box it uses maviapi's shared demo key: 30 requests a minute and 300 a day per network, plus 3 free API builds per 30 days. [Create a free key](https://maviapi.com/sign-up?utm_source=github&utm_medium=readme&utm_campaign=mcp) for more.
|
|
14
|
+
|
|
15
|
+
**Missing a site? Your agent can have it built.** `create_api` hands maviapi's build agent a URL and a description of the data you want; about half an hour later the new API is live and callable from the same session.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
### Claude Code
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
claude mcp add maviapi -- npx -y @maviapi/mcp
|
|
23
|
+
|
|
24
|
+
# with your own key
|
|
25
|
+
claude mcp add maviapi -e MAVIAPI_API_KEY=mvk_live_... -- npx -y @maviapi/mcp
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Claude Desktop, Cursor, Windsurf, and others
|
|
29
|
+
|
|
30
|
+
Add this to the client's MCP config (`claude_desktop_config.json`, `~/.cursor/mcp.json`, …):
|
|
31
|
+
|
|
32
|
+
```json
|
|
33
|
+
{
|
|
34
|
+
"mcpServers": {
|
|
35
|
+
"maviapi": {
|
|
36
|
+
"command": "npx",
|
|
37
|
+
"args": ["-y", "@maviapi/mcp"],
|
|
38
|
+
"env": { "MAVIAPI_API_KEY": "mvk_live_..." }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Leave out `env` to try it with the demo key.
|
|
45
|
+
|
|
46
|
+
### VS Code
|
|
47
|
+
|
|
48
|
+
`.vscode/mcp.json`:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"inputs": [{ "type": "promptString", "id": "maviapi-key", "description": "maviapi API key", "password": true }],
|
|
53
|
+
"servers": {
|
|
54
|
+
"maviapi": {
|
|
55
|
+
"command": "npx",
|
|
56
|
+
"args": ["-y", "@maviapi/mcp"],
|
|
57
|
+
"env": { "MAVIAPI_API_KEY": "${input:maviapi-key}" }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Tools
|
|
64
|
+
|
|
65
|
+
| Tool | What it does |
|
|
66
|
+
|------|--------------|
|
|
67
|
+
| `search_apis` | Find an API for a website or topic ("flights", "turkish news", "booking.com"). Empty query lists the whole catalog. |
|
|
68
|
+
| `get_api` | An API's endpoints, their parameters, and the fields each one returns. |
|
|
69
|
+
| `call_api` | Call an endpoint and get live JSON back. List endpoints return 10 results unless you pass `limit`. |
|
|
70
|
+
| `create_api` | No API for the site you need? Starts a build from a URL and a plain-language description, and returns a `request_id`. |
|
|
71
|
+
| `get_build_status` | Follows a build to `published` (then `get_api` and `call_api` work on it) or `failed`. Builds take about half an hour. |
|
|
72
|
+
|
|
73
|
+
A handful of generic tools keeps the agent's context small however large the catalog grows. If you rely on a few APIs, `MAVIAPI_TOOLS` also exposes each of their endpoints as its own typed tool, with a full input schema:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
claude mcp add maviapi -e MAVIAPI_TOOLS=booking,airbnb,kiwi -- npx -y @maviapi/mcp
|
|
77
|
+
# adds booking_search, booking_explore, airbnb_listing_by_id, kiwi_search, …
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## What you can ask
|
|
81
|
+
|
|
82
|
+
- "Cheapest flights from Istanbul to Berlin any day in the first week of December?" (Kiwi.com, FlightList)
|
|
83
|
+
- "Train or plane from London to Paris on Friday: which is cheaper?" (Trainline, Kiwi.com)
|
|
84
|
+
- "Top-rated restaurants in Istanbul on Tripadvisor, with review counts."
|
|
85
|
+
- "Bu hafta sonu İstanbul'da hangi konserler var?" (Bubilet)
|
|
86
|
+
- "What are gold and silver trading at right now?" (Selcoin)
|
|
87
|
+
- "What does 'serendipity' mean in Turkish? Give me every sense." (Sesli Sözlük)
|
|
88
|
+
|
|
89
|
+
`search_apis` with no query lists everything currently in the catalog. And for a site that is not there yet:
|
|
90
|
+
|
|
91
|
+
- "Build me an API for news.ycombinator.com with the front page stories, points and comment counts, then show me today's top 5."
|
|
92
|
+
|
|
93
|
+
## Configuration
|
|
94
|
+
|
|
95
|
+
| Variable | Default | Purpose |
|
|
96
|
+
|----------|---------|---------|
|
|
97
|
+
| `MAVIAPI_API_KEY` | shared demo key | Your key from the [maviapi dashboard](https://maviapi.com/dashboard). |
|
|
98
|
+
| `MAVIAPI_TOOLS` | none | Comma-separated API slugs to expose as typed per-endpoint tools, or `all`. |
|
|
99
|
+
| `MAVIAPI_BASE_URL` | `https://api.maviapi.com` | Point at another maviapi deployment. |
|
|
100
|
+
|
|
101
|
+
## Pricing
|
|
102
|
+
|
|
103
|
+
Each successful call uses one credit; failed calls are free. Building an API is free on any plan, within the daily build limit (10 a day per account with your own key). New accounts start with a 7-day trial of 5,000 credits, no card required. Plans are on [maviapi.com/pricing](https://maviapi.com/pricing?utm_source=github&utm_medium=readme&utm_campaign=mcp).
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
pnpm install
|
|
109
|
+
pnpm test # unit and protocol tests, offline
|
|
110
|
+
pnpm build
|
|
111
|
+
pnpm test:live # smoke test of the built server against the real API
|
|
112
|
+
pnpm inspect # open the MCP Inspector against the built server
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers over the public maviapi catalog: normalizing endpoint schema
|
|
3
|
+
* docs into tool input schemas, resolving names, building request paths, and
|
|
4
|
+
* rendering compact summaries for an agent to read. No network here.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Parameters kept out of the schemas an agent sees. `refresh` bypasses the
|
|
8
|
+
* endpoint cache and forces a fresh fetch of the source site: useful for a
|
|
9
|
+
* human debugging a stale result, wasteful when an agent sets it by reflex.
|
|
10
|
+
*/
|
|
11
|
+
const HIDDEN_PARAMS = new Set(["refresh"]);
|
|
12
|
+
/** Results per page when an agent omits `limit`: endpoints default to 50, which floods a context window. */
|
|
13
|
+
export const DEFAULT_LIMIT = 10;
|
|
14
|
+
/** Path parameter names, in order. Accepts both `/items/{id}` and `/items/:id`. */
|
|
15
|
+
export function pathParams(path) {
|
|
16
|
+
return path
|
|
17
|
+
.split("/")
|
|
18
|
+
.map(paramName)
|
|
19
|
+
.filter((name) => name !== null);
|
|
20
|
+
}
|
|
21
|
+
function paramName(segment) {
|
|
22
|
+
if (segment.startsWith(":") && segment.length > 1)
|
|
23
|
+
return segment.slice(1);
|
|
24
|
+
if (segment.startsWith("{") && segment.endsWith("}") && segment.length > 2) {
|
|
25
|
+
return segment.slice(1, -1);
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A readable endpoint name. Catalog slugs are inconsistent: some are a bare
|
|
31
|
+
* word ("hotel" for /hotel/{country}/{slug}), others the route itself
|
|
32
|
+
* ("listing/:id"). Static segments are kept and parameters become a `_by_`
|
|
33
|
+
* suffix, so /templates and /templates/:id stay distinct.
|
|
34
|
+
*/
|
|
35
|
+
export function endpointName(slug) {
|
|
36
|
+
const parts = slug.split("/").filter(Boolean);
|
|
37
|
+
const words = parts.filter((p) => paramName(p) === null);
|
|
38
|
+
const params = parts.map(paramName).filter((p) => p !== null);
|
|
39
|
+
const base = words.join("-") || "root";
|
|
40
|
+
return params.length ? `${base}_by_${params.join("_and_")}` : base;
|
|
41
|
+
}
|
|
42
|
+
export class MissingParamsError extends Error {
|
|
43
|
+
missing;
|
|
44
|
+
constructor(missing) {
|
|
45
|
+
super(`Missing required parameter${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}`);
|
|
46
|
+
this.missing = missing;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Substitute path parameters into an endpoint path. Returns the concrete path
|
|
51
|
+
* and the parameters left over, which go in the query string.
|
|
52
|
+
*/
|
|
53
|
+
export function fillPath(path, params) {
|
|
54
|
+
const query = { ...params };
|
|
55
|
+
const missing = [];
|
|
56
|
+
const segments = path.split("/").map((segment) => {
|
|
57
|
+
const name = paramName(segment);
|
|
58
|
+
if (name === null)
|
|
59
|
+
return segment;
|
|
60
|
+
const value = query[name];
|
|
61
|
+
delete query[name];
|
|
62
|
+
if (value === undefined || value === null || value === "") {
|
|
63
|
+
missing.push(name);
|
|
64
|
+
return segment;
|
|
65
|
+
}
|
|
66
|
+
return encodeURIComponent(String(value));
|
|
67
|
+
});
|
|
68
|
+
if (missing.length)
|
|
69
|
+
throw new MissingParamsError(missing);
|
|
70
|
+
return { path: segments.join("/"), query };
|
|
71
|
+
}
|
|
72
|
+
/** Encode query parameters. Arrays become comma lists, objects JSON. */
|
|
73
|
+
export function buildQuery(params) {
|
|
74
|
+
const search = new URLSearchParams();
|
|
75
|
+
for (const [key, value] of Object.entries(params)) {
|
|
76
|
+
if (value === undefined || value === null)
|
|
77
|
+
continue;
|
|
78
|
+
if (Array.isArray(value))
|
|
79
|
+
search.set(key, value.map(String).join(","));
|
|
80
|
+
else if (typeof value === "object")
|
|
81
|
+
search.set(key, JSON.stringify(value));
|
|
82
|
+
else
|
|
83
|
+
search.set(key, String(value));
|
|
84
|
+
}
|
|
85
|
+
const qs = search.toString();
|
|
86
|
+
return qs ? `?${qs}` : "";
|
|
87
|
+
}
|
|
88
|
+
function compareVersions(a, b) {
|
|
89
|
+
const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
90
|
+
const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
91
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
92
|
+
const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
93
|
+
if (diff !== 0)
|
|
94
|
+
return diff;
|
|
95
|
+
}
|
|
96
|
+
return 0;
|
|
97
|
+
}
|
|
98
|
+
/** The newest schema doc of an endpoint, if it has any. */
|
|
99
|
+
export function pickSchemaDoc(docs) {
|
|
100
|
+
if (!docs?.length)
|
|
101
|
+
return undefined;
|
|
102
|
+
return [...docs].sort((a, b) => compareVersions(b.version, a.version))[0];
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Reduce a property schema to the keywords tool clients understand. The
|
|
106
|
+
* catalog uses OpenAPI's singular `example`, which is not JSON Schema; it is
|
|
107
|
+
* folded into the description where a model will actually read it.
|
|
108
|
+
*/
|
|
109
|
+
export function cleanSchema(schema) {
|
|
110
|
+
const out = {};
|
|
111
|
+
if (schema.type !== undefined)
|
|
112
|
+
out.type = schema.type;
|
|
113
|
+
const parts = [schema.description?.trim() ?? ""];
|
|
114
|
+
if (schema.example !== undefined && schema.example !== schema.default) {
|
|
115
|
+
parts.push(`Example: ${JSON.stringify(schema.example)}`);
|
|
116
|
+
}
|
|
117
|
+
const description = sentences(parts);
|
|
118
|
+
if (description)
|
|
119
|
+
out.description = description;
|
|
120
|
+
for (const key of ["enum", "default", "format", "minimum", "maximum"]) {
|
|
121
|
+
if (schema[key] !== undefined)
|
|
122
|
+
out[key] = schema[key];
|
|
123
|
+
}
|
|
124
|
+
if (schema.items)
|
|
125
|
+
out.items = cleanSchema(schema.items);
|
|
126
|
+
if (schema.properties) {
|
|
127
|
+
out.properties = Object.fromEntries(Object.entries(schema.properties).map(([k, v]) => [k, cleanSchema(v)]));
|
|
128
|
+
if (schema.required?.length)
|
|
129
|
+
out.required = [...schema.required];
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
/** Join fragments as sentences: one period between them, never two. */
|
|
134
|
+
export function sentences(parts) {
|
|
135
|
+
return parts
|
|
136
|
+
.map((p) => p.trim())
|
|
137
|
+
.filter(Boolean)
|
|
138
|
+
.map((p, i, all) => (i < all.length - 1 && !/[.!?…]$/.test(p) ? `${p}.` : p))
|
|
139
|
+
.join(" ");
|
|
140
|
+
}
|
|
141
|
+
export function normalizeEndpoint(raw) {
|
|
142
|
+
const doc = pickSchemaDoc(raw.versions);
|
|
143
|
+
const input = doc?.input_schema ?? {};
|
|
144
|
+
const params = pathParams(raw.path);
|
|
145
|
+
const properties = {};
|
|
146
|
+
for (const [name, prop] of Object.entries(input.properties ?? {})) {
|
|
147
|
+
if (!HIDDEN_PARAMS.has(name))
|
|
148
|
+
properties[name] = cleanSchema(prop);
|
|
149
|
+
}
|
|
150
|
+
// A path parameter is always required, whether or not the doc says so.
|
|
151
|
+
for (const name of params)
|
|
152
|
+
properties[name] ??= { type: "string" };
|
|
153
|
+
const required = [
|
|
154
|
+
...new Set([...params, ...(input.required ?? []).filter((name) => name in properties)]),
|
|
155
|
+
];
|
|
156
|
+
const inputSchema = { type: "object", properties };
|
|
157
|
+
if (required.length)
|
|
158
|
+
inputSchema.required = required;
|
|
159
|
+
return {
|
|
160
|
+
name: endpointName(raw.slug),
|
|
161
|
+
slug: raw.slug,
|
|
162
|
+
path: raw.path,
|
|
163
|
+
method: raw.method.toUpperCase(),
|
|
164
|
+
description: (raw.description || doc?.description || doc?.title || "").trim(),
|
|
165
|
+
pathParams: params,
|
|
166
|
+
inputSchema,
|
|
167
|
+
outputSchema: doc?.output_schema ?? null,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/** Bare host of a URL or domain, without `www.`; null when it is not one. */
|
|
171
|
+
export function hostOf(value) {
|
|
172
|
+
if (!value)
|
|
173
|
+
return null;
|
|
174
|
+
const trimmed = value.trim();
|
|
175
|
+
if (!trimmed.includes("."))
|
|
176
|
+
return null;
|
|
177
|
+
try {
|
|
178
|
+
const url = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
|
|
179
|
+
return url.hostname.toLowerCase().replace(/^www\./, "");
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/** Resolve an API by slug, name, or the domain / URL of its site. */
|
|
186
|
+
export function findApi(apis, ref) {
|
|
187
|
+
const r = ref.trim().toLowerCase();
|
|
188
|
+
const host = hostOf(r);
|
|
189
|
+
return (apis.find((a) => a.slug.toLowerCase() === r) ??
|
|
190
|
+
apis.find((a) => a.name.toLowerCase() === r) ??
|
|
191
|
+
(host ? apis.find((a) => hostOf(a.target_url) === host) : undefined));
|
|
192
|
+
}
|
|
193
|
+
/** Resolve an endpoint by name, catalog slug, or path (leading slash optional). */
|
|
194
|
+
export function findEndpoint(endpoints, ref) {
|
|
195
|
+
const r = ref.trim().toLowerCase().replace(/^\/+/, "");
|
|
196
|
+
return (endpoints.find((e) => e.name.toLowerCase() === r) ??
|
|
197
|
+
endpoints.find((e) => e.slug.toLowerCase() === r) ??
|
|
198
|
+
endpoints.find((e) => e.path.toLowerCase().replace(/^\/+/, "") === r));
|
|
199
|
+
}
|
|
200
|
+
/** Rank catalog APIs against a free-text query. An empty query lists them all. */
|
|
201
|
+
export function searchApis(apis, query) {
|
|
202
|
+
const q = (query ?? "").trim().toLowerCase();
|
|
203
|
+
if (!q)
|
|
204
|
+
return [...apis];
|
|
205
|
+
const tokens = q.split(/\s+/).filter((t) => t.length > 1);
|
|
206
|
+
const queryHost = hostOf(q);
|
|
207
|
+
const scored = apis.map((api) => {
|
|
208
|
+
const slug = api.slug.toLowerCase();
|
|
209
|
+
const name = api.name.toLowerCase();
|
|
210
|
+
const host = hostOf(api.target_url) ?? "";
|
|
211
|
+
const description = (api.description ?? "").toLowerCase();
|
|
212
|
+
let score = queryHost && queryHost === host ? 20 : 0;
|
|
213
|
+
for (const token of tokens.map(singular)) {
|
|
214
|
+
if (slug === token)
|
|
215
|
+
score += 10;
|
|
216
|
+
else if (slug.includes(token))
|
|
217
|
+
score += 5;
|
|
218
|
+
if (host.includes(token))
|
|
219
|
+
score += 5;
|
|
220
|
+
if (name.includes(token))
|
|
221
|
+
score += 4;
|
|
222
|
+
if (description.includes(token))
|
|
223
|
+
score += 1;
|
|
224
|
+
}
|
|
225
|
+
return { api, score };
|
|
226
|
+
});
|
|
227
|
+
return scored
|
|
228
|
+
.filter((s) => s.score > 0)
|
|
229
|
+
.sort((a, b) => b.score - a.score)
|
|
230
|
+
.map((s) => s.api);
|
|
231
|
+
}
|
|
232
|
+
/** "hotels" -> "hotel", so a plural query still matches a singular description. Leaves "news" and "class" alone. */
|
|
233
|
+
function singular(token) {
|
|
234
|
+
return token.length > 4 && token.endsWith("s") && !token.endsWith("ss") ? token.slice(0, -1) : token;
|
|
235
|
+
}
|
|
236
|
+
function typeLabel(schema) {
|
|
237
|
+
const type = Array.isArray(schema.type) ? schema.type.join(" | ") : (schema.type ?? "any");
|
|
238
|
+
if (type === "array" && schema.items)
|
|
239
|
+
return `${typeLabel(schema.items)}[]`;
|
|
240
|
+
return type;
|
|
241
|
+
}
|
|
242
|
+
/** One line per input parameter, required ones first. */
|
|
243
|
+
export function describeParams(schema) {
|
|
244
|
+
const required = new Set(schema.required ?? []);
|
|
245
|
+
return Object.entries(schema.properties)
|
|
246
|
+
.sort(([a], [b]) => Number(required.has(b)) - Number(required.has(a)))
|
|
247
|
+
.map(([name, prop]) => {
|
|
248
|
+
const bits = [typeLabel(prop)];
|
|
249
|
+
if (required.has(name))
|
|
250
|
+
bits.push("required");
|
|
251
|
+
const notes = sentences([
|
|
252
|
+
prop.description ?? "",
|
|
253
|
+
prop.enum ? `One of: ${prop.enum.map((v) => JSON.stringify(v)).join(", ")}` : "",
|
|
254
|
+
prop.default !== undefined ? `Default: ${JSON.stringify(prop.default)}` : "",
|
|
255
|
+
]);
|
|
256
|
+
return `- ${name} (${bits.join(", ")})${notes ? `: ${notes}` : ""}`;
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Flatten a response schema into `path: type` lines (`data.items[].price:
|
|
261
|
+
* number`), so an agent knows which fields come back without reading a full
|
|
262
|
+
* JSON Schema document.
|
|
263
|
+
*/
|
|
264
|
+
export function outlineOutput(schema, maxLines = 40, maxDepth = 5) {
|
|
265
|
+
if (!schema)
|
|
266
|
+
return [];
|
|
267
|
+
const lines = [];
|
|
268
|
+
const walk = (node, prefix, depth) => {
|
|
269
|
+
for (const [key, child] of Object.entries(node.properties ?? {})) {
|
|
270
|
+
if (lines.length >= maxLines)
|
|
271
|
+
return;
|
|
272
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
273
|
+
if (child.properties && depth < maxDepth) {
|
|
274
|
+
walk(child, path, depth + 1);
|
|
275
|
+
}
|
|
276
|
+
else if (child.items?.properties && depth < maxDepth) {
|
|
277
|
+
walk(child.items, `${path}[]`, depth + 1);
|
|
278
|
+
}
|
|
279
|
+
else {
|
|
280
|
+
lines.push(`${path}: ${typeLabel(child)}`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
walk(schema, "", 0);
|
|
285
|
+
if (lines.length >= maxLines)
|
|
286
|
+
lines.push("…");
|
|
287
|
+
return lines;
|
|
288
|
+
}
|
|
289
|
+
/** MCP tool names allow [A-Za-z0-9_-], up to 64 characters. */
|
|
290
|
+
export function toolName(apiSlug, endpointSlug) {
|
|
291
|
+
return `${apiSlug}_${endpointSlug}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
|
|
292
|
+
}
|
|
293
|
+
/** Cut text to `max` characters. A `note` says why and what to do about it; without one, an ellipsis ends the cut. */
|
|
294
|
+
export function truncate(text, max, note) {
|
|
295
|
+
if (text.length <= max)
|
|
296
|
+
return text;
|
|
297
|
+
return note ? `${text.slice(0, max)}\n…[truncated: ${note}]` : `${text.slice(0, max - 1)}…`;
|
|
298
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { buildQuery, fillPath, normalizeEndpoint } from "./catalog.js";
|
|
2
|
+
import { VERSION } from "./config.js";
|
|
3
|
+
/** How long catalog and endpoint listings are reused before refetching. */
|
|
4
|
+
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
5
|
+
/** Bot-protected sources go through a real browser and can take a while. */
|
|
6
|
+
const CALL_TIMEOUT_MS = 120_000;
|
|
7
|
+
const CATALOG_TIMEOUT_MS = 20_000;
|
|
8
|
+
export class MaviapiError extends Error {
|
|
9
|
+
status;
|
|
10
|
+
constructor(message, status) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class MaviapiClient {
|
|
16
|
+
config;
|
|
17
|
+
fetchImpl;
|
|
18
|
+
catalog = null;
|
|
19
|
+
endpoints = new Map();
|
|
20
|
+
constructor(config, fetchImpl = fetch) {
|
|
21
|
+
this.config = config;
|
|
22
|
+
this.fetchImpl = fetchImpl;
|
|
23
|
+
}
|
|
24
|
+
/** Every API in the public catalog. */
|
|
25
|
+
listApis() {
|
|
26
|
+
if (!this.catalog || this.catalog.expires < Date.now()) {
|
|
27
|
+
const value = this.getJson("/v1/apis");
|
|
28
|
+
this.catalog = { value, expires: Date.now() + CACHE_TTL_MS };
|
|
29
|
+
value.catch(() => (this.catalog = null));
|
|
30
|
+
}
|
|
31
|
+
return this.catalog.value;
|
|
32
|
+
}
|
|
33
|
+
/** An API's endpoints on its active build, with their input and output schemas. */
|
|
34
|
+
listEndpoints(slug) {
|
|
35
|
+
const hit = this.endpoints.get(slug);
|
|
36
|
+
if (hit && hit.expires > Date.now())
|
|
37
|
+
return hit.value;
|
|
38
|
+
const value = this.getJson(`/v1/apis/${encodeURIComponent(slug)}/endpoints?include=schemas`).then((rows) => rows.map(normalizeEndpoint));
|
|
39
|
+
this.endpoints.set(slug, { value, expires: Date.now() + CACHE_TTL_MS });
|
|
40
|
+
value.catch(() => this.endpoints.delete(slug));
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
/** Drop the cached catalog, e.g. once a build has published a new API. */
|
|
44
|
+
invalidateCatalog() {
|
|
45
|
+
this.catalog = null;
|
|
46
|
+
}
|
|
47
|
+
/** Ask maviapi to build an API for a website (POST /v1/requests). */
|
|
48
|
+
createBuild(targetUrl, prompt) {
|
|
49
|
+
return this.send("POST", "/v1/requests", { targetUrl, ...(prompt && { prompt }) });
|
|
50
|
+
}
|
|
51
|
+
/** A build started with this key (GET /v1/requests/:id). */
|
|
52
|
+
getBuild(id) {
|
|
53
|
+
return this.send("GET", `/v1/requests/${encodeURIComponent(id)}`);
|
|
54
|
+
}
|
|
55
|
+
/** Call one endpoint through the maviapi gateway. */
|
|
56
|
+
async call(slug, endpoint, params) {
|
|
57
|
+
const { path, query } = fillPath(endpoint.path, params);
|
|
58
|
+
return this.send(endpoint.method, `/v1/sites/${encodeURIComponent(slug)}${path}${buildQuery(query)}`);
|
|
59
|
+
}
|
|
60
|
+
/** An authenticated request; the outcome is returned, never thrown, so callers can explain it. */
|
|
61
|
+
async send(method, path, json) {
|
|
62
|
+
const headers = { Authorization: `Bearer ${this.config.apiKey}` };
|
|
63
|
+
if (json !== undefined)
|
|
64
|
+
headers["Content-Type"] = "application/json";
|
|
65
|
+
const res = await this.request(`${this.config.baseUrl}${path}`, CALL_TIMEOUT_MS, {
|
|
66
|
+
method,
|
|
67
|
+
headers,
|
|
68
|
+
...(json !== undefined && { body: JSON.stringify(json) }),
|
|
69
|
+
});
|
|
70
|
+
const text = await res.text();
|
|
71
|
+
let body = text;
|
|
72
|
+
try {
|
|
73
|
+
body = JSON.parse(text);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Not JSON: hand the text back as is.
|
|
77
|
+
}
|
|
78
|
+
const retryAfter = Number.parseInt(res.headers.get("retry-after") ?? "", 10);
|
|
79
|
+
return {
|
|
80
|
+
status: res.status,
|
|
81
|
+
ok: res.ok,
|
|
82
|
+
body,
|
|
83
|
+
build: res.headers.get("x-maviapi-version"),
|
|
84
|
+
retryAfter: Number.isFinite(retryAfter) ? retryAfter : null,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
async getJson(path) {
|
|
88
|
+
const res = await this.request(`${this.config.baseUrl}${path}`, CATALOG_TIMEOUT_MS);
|
|
89
|
+
if (!res.ok) {
|
|
90
|
+
throw new MaviapiError(`maviapi catalog request failed (${res.status} on ${path})`, res.status);
|
|
91
|
+
}
|
|
92
|
+
return (await res.json());
|
|
93
|
+
}
|
|
94
|
+
async request(url, timeoutMs, init = {}) {
|
|
95
|
+
try {
|
|
96
|
+
return await this.fetchImpl(url, {
|
|
97
|
+
...init,
|
|
98
|
+
headers: {
|
|
99
|
+
Accept: "application/json",
|
|
100
|
+
"User-Agent": `maviapi-mcp/${VERSION}`,
|
|
101
|
+
...init.headers,
|
|
102
|
+
},
|
|
103
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
if (err instanceof Error && err.name === "TimeoutError") {
|
|
108
|
+
throw new MaviapiError(`maviapi did not answer within ${timeoutMs / 1000}s. Try again.`);
|
|
109
|
+
}
|
|
110
|
+
throw new MaviapiError(`Could not reach maviapi (${err instanceof Error ? err.message : String(err)}).`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const VERSION = "0.1.0";
|
|
2
|
+
export const DEFAULT_BASE_URL = "https://api.maviapi.com";
|
|
3
|
+
export const SITE_URL = "https://maviapi.com";
|
|
4
|
+
/**
|
|
5
|
+
* maviapi's public playground key. maviapi.com ships it to every visitor's
|
|
6
|
+
* browser so anyone can try the catalog without signing up, and the backend
|
|
7
|
+
* throttles it per client IP. It lets this server work with zero setup; a
|
|
8
|
+
* personal key (MAVIAPI_API_KEY) lifts the limit.
|
|
9
|
+
*/
|
|
10
|
+
export const PLAYGROUND_KEY = "mvk_test_playground_5f3c1a8d";
|
|
11
|
+
/** What the playground key allows from one network (one IPv4 address or IPv6 /64). */
|
|
12
|
+
export const PLAYGROUND_RATE_LIMIT = 30;
|
|
13
|
+
export const PLAYGROUND_DAILY_LIMIT = 300;
|
|
14
|
+
export const PLAYGROUND_FREE_BUILDS = 3;
|
|
15
|
+
export function loadConfig(env = process.env) {
|
|
16
|
+
const apiKey = env.MAVIAPI_API_KEY?.trim();
|
|
17
|
+
return {
|
|
18
|
+
baseUrl: (env.MAVIAPI_BASE_URL?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, ""),
|
|
19
|
+
apiKey: apiKey || PLAYGROUND_KEY,
|
|
20
|
+
usingPlaygroundKey: !apiKey,
|
|
21
|
+
dedicatedApis: parseToolList(env.MAVIAPI_TOOLS),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function parseToolList(raw) {
|
|
25
|
+
const items = (raw ?? "")
|
|
26
|
+
.split(",")
|
|
27
|
+
.map((s) => s.trim().toLowerCase())
|
|
28
|
+
.filter(Boolean);
|
|
29
|
+
return items.includes("all") ? "all" : items;
|
|
30
|
+
}
|
|
31
|
+
/** A maviapi.com link tagged so the site can attribute visits to this server. */
|
|
32
|
+
export function siteLink(path, campaign, params = {}) {
|
|
33
|
+
const url = new URL(path, SITE_URL);
|
|
34
|
+
for (const [k, v] of Object.entries(params))
|
|
35
|
+
url.searchParams.set(k, v);
|
|
36
|
+
url.searchParams.set("utm_source", "mcp");
|
|
37
|
+
url.searchParams.set("utm_medium", "mcp-server");
|
|
38
|
+
url.searchParams.set("utm_campaign", campaign);
|
|
39
|
+
return url.toString();
|
|
40
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
|
+
import { loadConfig } from "./config.js";
|
|
4
|
+
import { createServer } from "./server.js";
|
|
5
|
+
const config = loadConfig();
|
|
6
|
+
const server = createServer(config);
|
|
7
|
+
await server.connect(new StdioServerTransport());
|
|
8
|
+
// stdout carries the protocol, so diagnostics go to stderr.
|
|
9
|
+
console.error(config.usingPlaygroundKey
|
|
10
|
+
? "maviapi MCP server running on stdio with the shared demo key. Set MAVIAPI_API_KEY for a higher limit: https://maviapi.com/sign-up"
|
|
11
|
+
: "maviapi MCP server running on stdio.");
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import { MaviapiClient } from "./client.js";
|
|
4
|
+
import { VERSION } from "./config.js";
|
|
5
|
+
import { Toolset } from "./tools.js";
|
|
6
|
+
const INSTRUCTIONS = `maviapi gives you live, structured JSON from websites that have no official API (travel, e-commerce, news, events, finance and more).
|
|
7
|
+
Workflow: search_apis to find an API for a site or topic, get_api to read its endpoints and parameters, then call_api to fetch data.
|
|
8
|
+
If no API covers the site you need, create_api builds one (about half an hour; follow it with get_build_status).`;
|
|
9
|
+
/**
|
|
10
|
+
* The tool list is computed at request time (MAVIAPI_TOOLS adds one typed tool
|
|
11
|
+
* per endpoint, read from the live catalog), so the handlers are registered on
|
|
12
|
+
* the underlying protocol server rather than through McpServer.registerTool,
|
|
13
|
+
* which wants a static zod schema per tool.
|
|
14
|
+
*/
|
|
15
|
+
export function createServer(config, fetchImpl) {
|
|
16
|
+
const toolset = new Toolset(new MaviapiClient(config, fetchImpl));
|
|
17
|
+
const mcp = new McpServer({ name: "maviapi", title: "maviapi", version: VERSION, websiteUrl: "https://maviapi.com" }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
18
|
+
mcp.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await toolset.list() }));
|
|
19
|
+
mcp.server.setRequestHandler(CallToolRequestSchema, (request) => toolset.call(request.params.name, request.params.arguments ?? {}));
|
|
20
|
+
return mcp;
|
|
21
|
+
}
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
import { DEFAULT_LIMIT, MissingParamsError, describeParams, findApi, findEndpoint, hostOf, outlineOutput, searchApis, toolName, truncate, } from "./catalog.js";
|
|
2
|
+
import { MaviapiError } from "./client.js";
|
|
3
|
+
import { PLAYGROUND_DAILY_LIMIT, PLAYGROUND_FREE_BUILDS, PLAYGROUND_RATE_LIMIT, siteLink, } from "./config.js";
|
|
4
|
+
/** Cap on one tool result, so a large listing cannot swallow the agent's context. */
|
|
5
|
+
const MAX_RESULT_CHARS = 50_000;
|
|
6
|
+
const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true };
|
|
7
|
+
const GENERIC_TOOLS = [
|
|
8
|
+
{
|
|
9
|
+
name: "search_apis",
|
|
10
|
+
title: "Search maviapi APIs",
|
|
11
|
+
description: "Find a ready-made maviapi API for a website or topic, e.g. \"hotels\", \"flights\", \"booking.com\" or \"turkish news\". " +
|
|
12
|
+
"maviapi turns websites that have no official API into structured JSON endpoints, and monitors and repairs them when the site changes. " +
|
|
13
|
+
"Leave `query` empty to list every API. Next step: get_api, to see an API's endpoints and parameters.",
|
|
14
|
+
inputSchema: {
|
|
15
|
+
type: "object",
|
|
16
|
+
properties: {
|
|
17
|
+
query: { type: "string", description: "Website, domain, or topic to look for. Empty lists everything." },
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
annotations: { ...READ_ONLY, openWorldHint: false },
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "get_api",
|
|
24
|
+
title: "Show a maviapi API",
|
|
25
|
+
description: "Show one maviapi API's endpoints: what each returns, its parameters (required ones marked), and the fields in the response. " +
|
|
26
|
+
"Accepts the API slug from search_apis, or the site's domain (e.g. \"airbnb.com\"). Read this before call_api.",
|
|
27
|
+
inputSchema: {
|
|
28
|
+
type: "object",
|
|
29
|
+
properties: {
|
|
30
|
+
api: { type: "string", description: "API slug (e.g. \"booking\") or the site's domain." },
|
|
31
|
+
},
|
|
32
|
+
required: ["api"],
|
|
33
|
+
},
|
|
34
|
+
annotations: { ...READ_ONLY, openWorldHint: false },
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: "call_api",
|
|
38
|
+
title: "Call a maviapi endpoint",
|
|
39
|
+
description: "Fetch live, structured JSON from a website through a maviapi endpoint. " +
|
|
40
|
+
"`api` is the API slug (or domain), `endpoint` the endpoint name or path from get_api, and `params` its parameters, path parameters such as {id} included. " +
|
|
41
|
+
`List endpoints return ${DEFAULT_LIMIT} results unless you pass \`limit\`; page with \`offset\`. Each successful call uses one maviapi credit.`,
|
|
42
|
+
inputSchema: {
|
|
43
|
+
type: "object",
|
|
44
|
+
properties: {
|
|
45
|
+
api: { type: "string", description: "API slug (e.g. \"booking\") or the site's domain." },
|
|
46
|
+
endpoint: { type: "string", description: "Endpoint name (e.g. \"search\") or path (e.g. \"/search\")." },
|
|
47
|
+
params: {
|
|
48
|
+
type: "object",
|
|
49
|
+
description: "Endpoint parameters, as listed by get_api.",
|
|
50
|
+
additionalProperties: true,
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
required: ["api", "endpoint"],
|
|
54
|
+
},
|
|
55
|
+
annotations: { ...READ_ONLY, idempotentHint: false, openWorldHint: true },
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: "create_api",
|
|
59
|
+
title: "Build a new maviapi API",
|
|
60
|
+
description: "Get an API built for a website that no catalog API covers. maviapi's build agent studies the site and deploys a hosted, " +
|
|
61
|
+
"self-repairing JSON API from a plain-language description of the data you want. A build takes about half an hour: this " +
|
|
62
|
+
"returns a request_id at once, then follow it with get_build_status. " +
|
|
63
|
+
`With the shared demo key each network gets ${PLAYGROUND_FREE_BUILDS} free builds per 30 days.`,
|
|
64
|
+
inputSchema: {
|
|
65
|
+
type: "object",
|
|
66
|
+
properties: {
|
|
67
|
+
url: { type: "string", description: "The website, e.g. \"https://news.ycombinator.com\"." },
|
|
68
|
+
description: {
|
|
69
|
+
type: "string",
|
|
70
|
+
description: "The data wanted from the site, as specific as you can: pages, fields, filters. " +
|
|
71
|
+
"E.g. \"front-page stories with title, url, points, comment count and author\".",
|
|
72
|
+
},
|
|
73
|
+
build_anyway: {
|
|
74
|
+
type: "boolean",
|
|
75
|
+
description: "Build even though the catalog already has an API for this site (it lacks what you need).",
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
required: ["url", "description"],
|
|
79
|
+
},
|
|
80
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
name: "get_build_status",
|
|
84
|
+
title: "Check a maviapi build",
|
|
85
|
+
description: "Progress of a build started with create_api: queued, building, deploying, published, or failed. " +
|
|
86
|
+
"Once published it names the new API's slug, ready for get_api and call_api. Builds take about half an hour, " +
|
|
87
|
+
"so check back every few minutes rather than in a tight loop.",
|
|
88
|
+
inputSchema: {
|
|
89
|
+
type: "object",
|
|
90
|
+
properties: {
|
|
91
|
+
request_id: { type: "string", description: "The request_id create_api returned." },
|
|
92
|
+
},
|
|
93
|
+
required: ["request_id"],
|
|
94
|
+
},
|
|
95
|
+
annotations: { ...READ_ONLY, idempotentHint: false, openWorldHint: false },
|
|
96
|
+
},
|
|
97
|
+
];
|
|
98
|
+
/** "45 seconds", "30 minutes", "29 days": the largest unit that fits. */
|
|
99
|
+
export function humanDuration(seconds) {
|
|
100
|
+
const units = [["day", 86_400], ["hour", 3_600], ["minute", 60]];
|
|
101
|
+
for (const [unit, size] of units) {
|
|
102
|
+
if (seconds >= size) {
|
|
103
|
+
const n = Math.round(seconds / size);
|
|
104
|
+
return `${n} ${unit}${n === 1 ? "" : "s"}`;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return `${seconds} second${seconds === 1 ? "" : "s"}`;
|
|
108
|
+
}
|
|
109
|
+
/** A failure worth showing the agent verbatim: bad input, unknown names. */
|
|
110
|
+
class UserError extends Error {
|
|
111
|
+
}
|
|
112
|
+
function text(body) {
|
|
113
|
+
return { content: [{ type: "text", text: body }] };
|
|
114
|
+
}
|
|
115
|
+
function failure(body) {
|
|
116
|
+
return { content: [{ type: "text", text: body }], isError: true };
|
|
117
|
+
}
|
|
118
|
+
function stringArg(args, name, required = false) {
|
|
119
|
+
const value = args[name];
|
|
120
|
+
if (typeof value === "string" && value.trim())
|
|
121
|
+
return value.trim();
|
|
122
|
+
if (value === undefined || value === null || value === "") {
|
|
123
|
+
if (required)
|
|
124
|
+
throw new UserError(`\`${name}\` is required.`);
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
throw new UserError(`\`${name}\` must be a string.`);
|
|
128
|
+
}
|
|
129
|
+
/** Models sometimes send `params` as a JSON string; accept that too. */
|
|
130
|
+
function objectArg(args, name) {
|
|
131
|
+
let value = args[name];
|
|
132
|
+
if (value === undefined || value === null || value === "")
|
|
133
|
+
return {};
|
|
134
|
+
if (typeof value === "string") {
|
|
135
|
+
try {
|
|
136
|
+
value = JSON.parse(value);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
throw new UserError(`\`${name}\` must be an object, e.g. {"q": "istanbul"}.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
143
|
+
throw new UserError(`\`${name}\` must be an object, e.g. {"q": "istanbul"}.`);
|
|
144
|
+
}
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
export class Toolset {
|
|
148
|
+
client;
|
|
149
|
+
config;
|
|
150
|
+
log;
|
|
151
|
+
dedicated = null;
|
|
152
|
+
nudged = false;
|
|
153
|
+
constructor(client, config = client.config, log = (m) => console.error(m)) {
|
|
154
|
+
this.client = client;
|
|
155
|
+
this.config = config;
|
|
156
|
+
this.log = log;
|
|
157
|
+
}
|
|
158
|
+
async list() {
|
|
159
|
+
const dedicated = await this.dedicatedTools();
|
|
160
|
+
return [...GENERIC_TOOLS, ...[...dedicated.values()].map((d) => d.tool)];
|
|
161
|
+
}
|
|
162
|
+
async call(name, args = {}) {
|
|
163
|
+
try {
|
|
164
|
+
switch (name) {
|
|
165
|
+
case "search_apis":
|
|
166
|
+
return await this.searchApis(args);
|
|
167
|
+
case "get_api":
|
|
168
|
+
return await this.getApi(args);
|
|
169
|
+
case "call_api":
|
|
170
|
+
return await this.callApi(args);
|
|
171
|
+
case "create_api":
|
|
172
|
+
return await this.createApi(args);
|
|
173
|
+
case "get_build_status":
|
|
174
|
+
return await this.getBuildStatus(args);
|
|
175
|
+
}
|
|
176
|
+
const dedicated = (await this.dedicatedTools()).get(name);
|
|
177
|
+
if (!dedicated)
|
|
178
|
+
throw new UserError(`Unknown tool "${name}".`);
|
|
179
|
+
return await this.run(dedicated.slug, dedicated.endpoint, args);
|
|
180
|
+
}
|
|
181
|
+
catch (err) {
|
|
182
|
+
if (err instanceof UserError || err instanceof MissingParamsError || err instanceof MaviapiError) {
|
|
183
|
+
return failure(err.message);
|
|
184
|
+
}
|
|
185
|
+
this.log(`maviapi-mcp: ${name} failed: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
|
|
186
|
+
return failure(`Unexpected error: ${err instanceof Error ? err.message : String(err)}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async searchApis(args) {
|
|
190
|
+
const query = stringArg(args, "query");
|
|
191
|
+
const apis = await this.client.listApis();
|
|
192
|
+
const hits = searchApis(apis, query);
|
|
193
|
+
if (!hits.length) {
|
|
194
|
+
return text(`No catalog API matches "${query}". ${apis.length} APIs are available: call search_apis with no query to list them all. ` +
|
|
195
|
+
"If the site you need is missing, create_api can build an API for it.");
|
|
196
|
+
}
|
|
197
|
+
const header = query ? `${hits.length} API(s) match "${query}":` : `${apis.length} APIs in the maviapi catalog:`;
|
|
198
|
+
const lines = hits.map((api) => {
|
|
199
|
+
const host = hostOf(api.target_url);
|
|
200
|
+
const description = truncate((api.description ?? "").trim(), 220);
|
|
201
|
+
return `- ${api.slug}: ${api.name}${host ? ` (${host})` : ""}. ${description}`;
|
|
202
|
+
});
|
|
203
|
+
const others = apis.filter((api) => !hits.includes(api)).map((api) => api.slug);
|
|
204
|
+
if (others.length)
|
|
205
|
+
lines.push("", `Other APIs in the catalog: ${others.join(", ")}.`);
|
|
206
|
+
return text([header, ...lines, "", "Next: get_api with a slug to see its endpoints."].join("\n"));
|
|
207
|
+
}
|
|
208
|
+
async resolveApi(ref) {
|
|
209
|
+
const apis = await this.client.listApis();
|
|
210
|
+
const api = findApi(apis, ref);
|
|
211
|
+
if (!api) {
|
|
212
|
+
const suggestions = searchApis(apis, ref).slice(0, 3).map((a) => a.slug);
|
|
213
|
+
throw new UserError(`No maviapi API named "${ref}".` +
|
|
214
|
+
(suggestions.length ? ` Did you mean: ${suggestions.join(", ")}?` : " Use search_apis to find one.") +
|
|
215
|
+
" If the site is not in the catalog, create_api can build one.");
|
|
216
|
+
}
|
|
217
|
+
return api;
|
|
218
|
+
}
|
|
219
|
+
async getApi(args) {
|
|
220
|
+
const api = await this.resolveApi(stringArg(args, "api", true));
|
|
221
|
+
const endpoints = await this.client.listEndpoints(api.slug);
|
|
222
|
+
const out = [`# ${api.name} (${api.slug})`];
|
|
223
|
+
if (api.target_url)
|
|
224
|
+
out.push(`Site: ${api.target_url}`);
|
|
225
|
+
if (api.description)
|
|
226
|
+
out.push(api.description.trim());
|
|
227
|
+
for (const ep of endpoints) {
|
|
228
|
+
out.push("", `## ${ep.name}: ${ep.method} ${ep.path}`);
|
|
229
|
+
if (ep.description)
|
|
230
|
+
out.push(ep.description);
|
|
231
|
+
const params = describeParams(ep.inputSchema);
|
|
232
|
+
out.push(params.length ? "Parameters:" : "Parameters: none");
|
|
233
|
+
out.push(...params);
|
|
234
|
+
const fields = outlineOutput(ep.outputSchema, 25);
|
|
235
|
+
if (fields.length)
|
|
236
|
+
out.push("Returns:", ...fields.map((f) => ` ${f}`));
|
|
237
|
+
}
|
|
238
|
+
const first = endpoints[0];
|
|
239
|
+
if (first) {
|
|
240
|
+
out.push("", `Call one with call_api, e.g. {"api": "${api.slug}", "endpoint": "${first.name}", "params": {…}}.`);
|
|
241
|
+
}
|
|
242
|
+
return text(truncate(out.join("\n"), MAX_RESULT_CHARS, "too many endpoints to show"));
|
|
243
|
+
}
|
|
244
|
+
async callApi(args) {
|
|
245
|
+
const api = await this.resolveApi(stringArg(args, "api", true));
|
|
246
|
+
const ref = stringArg(args, "endpoint", true);
|
|
247
|
+
const params = objectArg(args, "params");
|
|
248
|
+
const endpoints = await this.client.listEndpoints(api.slug);
|
|
249
|
+
const endpoint = findEndpoint(endpoints, ref);
|
|
250
|
+
if (!endpoint) {
|
|
251
|
+
throw new UserError(`${api.slug} has no endpoint "${ref}". Available: ${endpoints.map((e) => e.name).join(", ")}. ` +
|
|
252
|
+
`get_api "${api.slug}" lists their parameters.`);
|
|
253
|
+
}
|
|
254
|
+
return this.run(api.slug, endpoint, params);
|
|
255
|
+
}
|
|
256
|
+
/** Call an endpoint and turn the outcome into something an agent can act on. */
|
|
257
|
+
async run(slug, endpoint, input) {
|
|
258
|
+
const params = { ...input };
|
|
259
|
+
if ("limit" in endpoint.inputSchema.properties && params.limit === undefined) {
|
|
260
|
+
params.limit = DEFAULT_LIMIT;
|
|
261
|
+
}
|
|
262
|
+
const missing = (endpoint.inputSchema.required ?? []).filter((name) => params[name] === undefined || params[name] === null || params[name] === "");
|
|
263
|
+
if (missing.length)
|
|
264
|
+
throw new MissingParamsError(missing);
|
|
265
|
+
const result = await this.client.call(slug, endpoint, params);
|
|
266
|
+
if (!result.ok)
|
|
267
|
+
return failure(this.describeFailure(result));
|
|
268
|
+
const body = typeof result.body === "string" ? result.body : JSON.stringify(result.body);
|
|
269
|
+
let out = truncate(body, MAX_RESULT_CHARS, "pass a smaller limit, or page with offset");
|
|
270
|
+
if (this.config.usingPlaygroundKey && !this.nudged) {
|
|
271
|
+
this.nudged = true;
|
|
272
|
+
out +=
|
|
273
|
+
`\n\n(Served with maviapi's shared demo key, limited to ${PLAYGROUND_RATE_LIMIT} requests a minute. ` +
|
|
274
|
+
`For a higher limit, create a free key at ${siteLink("/sign-up", "demo_key_notice")} and set MAVIAPI_API_KEY.)`;
|
|
275
|
+
}
|
|
276
|
+
return text(out);
|
|
277
|
+
}
|
|
278
|
+
describeFailure({ status, body, retryAfter }) {
|
|
279
|
+
const payload = (body && typeof body === "object" ? body : {});
|
|
280
|
+
const message = payload.message ?? (typeof body === "string" ? body.slice(0, 300) : "");
|
|
281
|
+
const code = payload.error ? `${payload.error}: ` : "";
|
|
282
|
+
if (status === 401) {
|
|
283
|
+
return this.config.usingPlaygroundKey
|
|
284
|
+
? `maviapi rejected the shared demo key (${message}). Create a free key at ${siteLink("/sign-up", "auth_error")} and set MAVIAPI_API_KEY in this server's config.`
|
|
285
|
+
: `maviapi rejected MAVIAPI_API_KEY (${message}). Create or copy a key at ${siteLink("/dashboard", "auth_error")} and update this server's config.`;
|
|
286
|
+
}
|
|
287
|
+
if (status === 402) {
|
|
288
|
+
return `${message || "This account is out of maviapi credits."} Plans: ${siteLink("/pricing", "credit_limit")}`;
|
|
289
|
+
}
|
|
290
|
+
if (status === 429) {
|
|
291
|
+
const wait = retryAfter ? ` Retry in ${humanDuration(retryAfter)}.` : "";
|
|
292
|
+
return this.config.usingPlaygroundKey
|
|
293
|
+
? `The shared demo key's limit for this network is used up (${PLAYGROUND_RATE_LIMIT} requests a minute, ` +
|
|
294
|
+
`${PLAYGROUND_DAILY_LIMIT} a day).${wait} For a higher limit, tell the user they can create a free maviapi ` +
|
|
295
|
+
`account (5,000 credits, no card) at ${siteLink("/sign-up", "rate_limit")} and set MAVIAPI_API_KEY.`
|
|
296
|
+
: `Rate limit reached for this API key (${message}).${wait || " Wait a minute and retry."}`;
|
|
297
|
+
}
|
|
298
|
+
if (status >= 500) {
|
|
299
|
+
return (`The source site could not be fetched (${status} ${code}${message}). This is often temporary, or the site rejected ` +
|
|
300
|
+
"these parameters. maviapi monitors its endpoints and repairs them when a site changes, so retry later or with different parameters.");
|
|
301
|
+
}
|
|
302
|
+
return `maviapi returned ${status} (${code}${message || "no details"}).`;
|
|
303
|
+
}
|
|
304
|
+
async createApi(args) {
|
|
305
|
+
const url = stringArg(args, "url", true);
|
|
306
|
+
const description = stringArg(args, "description", true);
|
|
307
|
+
const host = hostOf(url);
|
|
308
|
+
if (!host)
|
|
309
|
+
throw new UserError(`"${url}" is not a website URL. Pass one like https://example.com.`);
|
|
310
|
+
const target = url.includes("://") ? url : `https://${url}`;
|
|
311
|
+
if (!target.startsWith("http://") && !target.startsWith("https://")) {
|
|
312
|
+
throw new UserError("Only http and https websites are supported.");
|
|
313
|
+
}
|
|
314
|
+
if (args.build_anyway !== true) {
|
|
315
|
+
const existing = (await this.client.listApis()).find((a) => hostOf(a.target_url) === host);
|
|
316
|
+
if (existing) {
|
|
317
|
+
return text(`maviapi already has an API for ${host}: "${existing.slug}" (${existing.name}). Call get_api with "${existing.slug}" ` +
|
|
318
|
+
"to see what it returns. If it lacks the data you need, call create_api again with build_anyway: true.");
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const result = await this.client.createBuild(target, description);
|
|
322
|
+
const payload = (result.body && typeof result.body === "object" ? result.body : {});
|
|
323
|
+
if (result.ok && payload.id) {
|
|
324
|
+
const out = [
|
|
325
|
+
`Build started for ${payload.domain ?? host}.`,
|
|
326
|
+
`request_id: ${payload.id}`,
|
|
327
|
+
`status: ${payload.status ?? "queued"}`,
|
|
328
|
+
"",
|
|
329
|
+
"A build usually takes about half an hour. Check it with get_build_status (every few minutes is plenty); " +
|
|
330
|
+
"once it is published, get_api and call_api can use the new API.",
|
|
331
|
+
];
|
|
332
|
+
if (this.config.usingPlaygroundKey) {
|
|
333
|
+
out.push("", `(Built with the shared demo key: each network gets ${PLAYGROUND_FREE_BUILDS} free builds per 30 days. ` +
|
|
334
|
+
`A free account at ${siteLink("/sign-up", "create_api_started")} builds more.)`);
|
|
335
|
+
}
|
|
336
|
+
return text(out.join("\n"));
|
|
337
|
+
}
|
|
338
|
+
if (result.status === 429 || result.status === 503) {
|
|
339
|
+
const wait = result.retryAfter && result.status === 503 ? ` (retry in ${humanDuration(result.retryAfter)})` : "";
|
|
340
|
+
return failure(`${payload.message ?? "maviapi cannot start a build right now."}${wait}\n\n` +
|
|
341
|
+
"Tell the user they can sign up free and build it from their own account here, with the site already filled in:\n" +
|
|
342
|
+
siteLink("/apis/request", "create_api_limit", { url: target }));
|
|
343
|
+
}
|
|
344
|
+
if (result.status === 400) {
|
|
345
|
+
return failure(payload.message ?? "maviapi rejected this build request.");
|
|
346
|
+
}
|
|
347
|
+
return failure(this.describeFailure(result));
|
|
348
|
+
}
|
|
349
|
+
async getBuildStatus(args) {
|
|
350
|
+
const id = stringArg(args, "request_id", true);
|
|
351
|
+
const result = await this.client.getBuild(id);
|
|
352
|
+
if (result.status === 404) {
|
|
353
|
+
return failure(`No build "${id}" was started with this API key. Use the request_id create_api returned.`);
|
|
354
|
+
}
|
|
355
|
+
if (!result.ok)
|
|
356
|
+
return failure(this.describeFailure(result));
|
|
357
|
+
const build = result.body;
|
|
358
|
+
const out = [`Build ${build.id} for ${build.domain}: ${build.status}.`];
|
|
359
|
+
const recent = (build.progress ?? []).slice(-3).map((p) => `- ${p.message}`);
|
|
360
|
+
if (recent.length)
|
|
361
|
+
out.push("Latest progress:", ...recent);
|
|
362
|
+
if (build.status === "published" && build.slug) {
|
|
363
|
+
// The new API is in the catalog now; make search_apis and get_api see it.
|
|
364
|
+
this.client.invalidateCatalog();
|
|
365
|
+
out.push("", `The API is live as "${build.slug}". Call get_api with "${build.slug}" to see its endpoints.`);
|
|
366
|
+
}
|
|
367
|
+
else if (build.status === "failed") {
|
|
368
|
+
out.push("", `It failed: ${build.error ?? "no reason given"}. A narrower description, or a different page of the site, may build where this did not.`);
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
out.push("", "Still in progress. Check again in a few minutes.");
|
|
372
|
+
}
|
|
373
|
+
return text(out.join("\n"));
|
|
374
|
+
}
|
|
375
|
+
/** Typed per-endpoint tools for the APIs named in MAVIAPI_TOOLS. */
|
|
376
|
+
dedicatedTools() {
|
|
377
|
+
const wanted = this.config.dedicatedApis;
|
|
378
|
+
if (wanted !== "all" && wanted.length === 0)
|
|
379
|
+
return Promise.resolve(new Map());
|
|
380
|
+
this.dedicated ??= this.buildDedicatedTools(wanted).catch((err) => {
|
|
381
|
+
this.dedicated = null;
|
|
382
|
+
this.log(`maviapi-mcp: could not load per-endpoint tools (${err instanceof Error ? err.message : err}); serving the generic tools only.`);
|
|
383
|
+
return new Map();
|
|
384
|
+
});
|
|
385
|
+
return this.dedicated;
|
|
386
|
+
}
|
|
387
|
+
async buildDedicatedTools(wanted) {
|
|
388
|
+
const apis = await this.client.listApis();
|
|
389
|
+
const selected = [];
|
|
390
|
+
if (wanted === "all") {
|
|
391
|
+
selected.push(...apis);
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
for (const ref of wanted) {
|
|
395
|
+
const api = findApi(apis, ref);
|
|
396
|
+
if (api)
|
|
397
|
+
selected.push(api);
|
|
398
|
+
else
|
|
399
|
+
this.log(`maviapi-mcp: MAVIAPI_TOOLS names "${ref}", which is not in the catalog; skipping it.`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const tools = new Map();
|
|
403
|
+
const perApi = await Promise.all(selected.map(async (api) => ({ api, endpoints: await this.client.listEndpoints(api.slug) })));
|
|
404
|
+
for (const { api, endpoints } of perApi) {
|
|
405
|
+
for (const endpoint of endpoints) {
|
|
406
|
+
const name = toolName(api.slug, endpoint.name);
|
|
407
|
+
if (tools.has(name))
|
|
408
|
+
continue;
|
|
409
|
+
tools.set(name, {
|
|
410
|
+
slug: api.slug,
|
|
411
|
+
endpoint,
|
|
412
|
+
tool: {
|
|
413
|
+
name,
|
|
414
|
+
title: `${api.name}: ${endpoint.name}`,
|
|
415
|
+
description: truncate(`${api.name} via maviapi: ${endpoint.description || `${endpoint.method} ${endpoint.path}`}` +
|
|
416
|
+
("limit" in endpoint.inputSchema.properties ? ` Returns ${DEFAULT_LIMIT} results unless you pass limit.` : ""), 1000),
|
|
417
|
+
inputSchema: endpoint.inputSchema,
|
|
418
|
+
annotations: { ...READ_ONLY, idempotentHint: false, openWorldHint: true },
|
|
419
|
+
},
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return tools;
|
|
424
|
+
}
|
|
425
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maviapi/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MCP server that gives AI agents live, structured JSON from websites with no official API (Booking.com, Airbnb, Tripadvisor, Kiwi.com, Hepsiburada and more), through self-repairing maviapi endpoints.",
|
|
5
|
+
"mcpName": "io.github.kuzenlabs/maviapi-mcp",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"maviapi-mcp": "dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.build.json && chmod +x dist/index.js",
|
|
20
|
+
"dev": "tsx src/index.ts",
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"test:live": "MAVIAPI_LIVE=1 vitest run test/live.test.ts",
|
|
24
|
+
"inspect": "pnpm build && npx @modelcontextprotocol/inspector node dist/index.js",
|
|
25
|
+
"prepublishOnly": "pnpm typecheck && pnpm test && pnpm build",
|
|
26
|
+
"prepare": "npm run build"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"mcp",
|
|
30
|
+
"model-context-protocol",
|
|
31
|
+
"mcp-server",
|
|
32
|
+
"maviapi",
|
|
33
|
+
"web-scraping",
|
|
34
|
+
"web-data",
|
|
35
|
+
"api",
|
|
36
|
+
"ai-agents",
|
|
37
|
+
"claude",
|
|
38
|
+
"cursor"
|
|
39
|
+
],
|
|
40
|
+
"author": "KuzenLabs <hello@maviapi.com>",
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"homepage": "https://maviapi.com",
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git+https://github.com/kuzenlabs/maviapi-mcp.git"
|
|
46
|
+
},
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/kuzenlabs/maviapi-mcp/issues"
|
|
49
|
+
},
|
|
50
|
+
"packageManager": "pnpm@12.18.0",
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
53
|
+
"zod": "^4.6.7"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/node": "^22.20.5",
|
|
57
|
+
"tsx": "^4.23.15",
|
|
58
|
+
"typescript": "^5.9.3",
|
|
59
|
+
"vitest": "^5.1.0"
|
|
60
|
+
}
|
|
61
|
+
}
|