@maviapi/mcp 0.1.1 → 0.2.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/README.md CHANGED
@@ -12,17 +12,28 @@ Agents are bad at the web. Browsing is slow, burns tokens on raw HTML, and stall
12
12
 
13
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
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.
15
+ **Missing a site? Your agent can start a draft.** `create_api` hands maviapi's build agent a URL and a description of the data you want. Follow progress with `get_build_status`, then review and publish the draft from your account before calling the public API. Build duration depends on the site and requested endpoints.
16
16
 
17
17
  ## Install
18
18
 
19
19
  ### Claude Code
20
20
 
21
+ Install it as a plugin from this repo's marketplace:
22
+
23
+ ```
24
+ /plugin marketplace add kuzenlabs/maviapi-mcp
25
+ /plugin install maviapi@maviapi
26
+ ```
27
+
28
+ The plugin reads `MAVIAPI_API_KEY` (and `MAVIAPI_TOOLS`) from your environment, so export your key before starting Claude Code to use it instead of the demo key.
29
+
30
+ Or add the server directly. Quote the package name so zsh doesn't offer to "correct" the `@` scope away:
31
+
21
32
  ```bash
22
- claude mcp add maviapi -- npx -y @maviapi/mcp
33
+ claude mcp add maviapi -- npx -y '@maviapi/mcp'
23
34
 
24
35
  # with your own key
25
- claude mcp add maviapi -e MAVIAPI_API_KEY=mvk_live_... -- npx -y @maviapi/mcp
36
+ claude mcp add maviapi -e MAVIAPI_API_KEY=mvk_live_... -- npx -y '@maviapi/mcp'
26
37
  ```
27
38
 
28
39
  ### Claude Desktop, Cursor, Windsurf, and others
@@ -68,12 +79,23 @@ Leave out `env` to try it with the demo key.
68
79
  | `get_api` | An API's endpoints, their parameters, and the fields each one returns. |
69
80
  | `call_api` | Call an endpoint and get live JSON back. List endpoints return 10 results unless you pass `limit`. |
70
81
  | `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. |
82
+ | `get_build_status` | Where a build is: its phase, each endpoint with its test results or what went wrong, and what the build said last. `wait_seconds` returns as soon as something changes. A finished build is not public until it is published. |
83
+ | `request_endpoint` | Add one endpoint to an API that exists, or a changed version of one (it ships beside the old one, e.g. `/search-v2`). Previews first; `confirm: true` starts the build. |
84
+ | `list_requests` | Your API and endpoint requests, with their status. |
85
+ | `send_request_message` | Tell a build something in plain words: add detail, fix or drop a failed endpoint, try again. |
86
+ | `call_draft` | Call an endpoint of a draft before it is published. Costs no credits. |
87
+ | `publish_request` | Make a finished request live. Needs a key with the `requests:publish` permission. |
88
+ | `cancel_request` | Stop the build running for a request. |
89
+ | `report_endpoint_issue` | Report an endpoint that fails, comes back empty or repeats the same page. maviapi replays the call and checks the endpoint itself: a fault its own check confirms is repaired in place, the rest go to a person. You can report an API you have called with your own key. With no arguments it lists your reports. |
90
+ | `get_key_info` | What the configured key may do: permissions, plan, remaining credits, limits. |
91
+ | `get_changelog` | An API's versions, newest first, with what changed. `call_api` takes a `version`. |
92
+
93
+ The request tools need your own API key with request permissions. A key only calls data APIs unless you turn permissions on when you create it on the [keys page](https://maviapi.com/dashboard/keys): "Start and manage builds" for asking, steering, cancelling and reporting, and "Publish builds" for `publish_request`. `create_api` works with any key. Every rule (who may publish, one build per API at a time with up to 3 requests in line, the daily limits) is enforced by maviapi, not by this server.
72
94
 
73
95
  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
96
 
75
97
  ```bash
76
- claude mcp add maviapi -e MAVIAPI_TOOLS=booking,airbnb,kiwi -- npx -y @maviapi/mcp
98
+ claude mcp add maviapi -e MAVIAPI_TOOLS=booking,airbnb,kiwi -- npx -y '@maviapi/mcp'
77
99
  # adds booking_search, booking_explore, airbnb_listing_by_id, kiwi_search, …
78
100
  ```
79
101
 
@@ -88,7 +110,13 @@ claude mcp add maviapi -e MAVIAPI_TOOLS=booking,airbnb,kiwi -- npx -y @maviapi/m
88
110
 
89
111
  `search_apis` with no query lists everything currently in the catalog. And for a site that is not there yet:
90
112
 
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."
113
+ - "Start an API build for news.ycombinator.com with front-page stories, points and comment counts."
114
+
115
+ And for an API that exists but lacks something:
116
+
117
+ - "Tripadvisor has no endpoint for a hotel's reviews. Ask for one, tell me when it is ready, and show me a sample before you publish it."
118
+
119
+ Use your own account and API key when you need to review and publish a build from the [dashboard](https://maviapi.com/dashboard/requests). The shared demo key can start builds, but does not provide an owner dashboard session for them. If an API is already public, `get_api` and `call_api` use its current public build; a newly completed candidate may still await publication.
92
120
 
93
121
  ## Configuration
94
122
 
package/dist/client.js CHANGED
@@ -40,7 +40,7 @@ export class MaviapiClient {
40
40
  value.catch(() => this.endpoints.delete(slug));
41
41
  return value;
42
42
  }
43
- /** Drop the cached catalog, e.g. once a build has published a new API. */
43
+ /** Drop the cached catalog before checking whether an API is public. */
44
44
  invalidateCatalog() {
45
45
  this.catalog = null;
46
46
  }
@@ -52,14 +52,73 @@ export class MaviapiClient {
52
52
  getBuild(id) {
53
53
  return this.send("GET", `/v1/requests/${encodeURIComponent(id)}`);
54
54
  }
55
- /** Call one endpoint through the maviapi gateway. */
56
- async call(slug, endpoint, params) {
55
+ /** Call one endpoint through the maviapi gateway, on the live build or on `version`. */
56
+ async call(slug, endpoint, params, version) {
57
57
  const { path, query } = fillPath(endpoint.path, params);
58
- return this.send(endpoint.method, `/v1/sites/${encodeURIComponent(slug)}${path}${buildQuery(query)}`);
58
+ return this.send(endpoint.method, `/v1/sites/${encodeURIComponent(slug)}${path}${buildQuery(query)}`, undefined, version === undefined ? {} : { "x-maviapi-version": String(version) });
59
+ }
60
+ /** Drop what is cached about one API, after a request changed it. */
61
+ invalidateApi(slug) {
62
+ this.endpoints.delete(slug);
63
+ this.catalog = null;
64
+ }
65
+ /** Each endpoint's current health (GET /v1/apis/:slug/health). */
66
+ apiHealth(slug) {
67
+ return this.send("GET", `/v1/apis/${encodeURIComponent(slug)}/health`);
68
+ }
69
+ /** The endpoints being built for an API right now (GET /v1/apis/:slug/endpoint-requests). */
70
+ buildingEndpoints(slug) {
71
+ return this.send("GET", `/v1/apis/${encodeURIComponent(slug)}/endpoint-requests`);
72
+ }
73
+ /** Every build of an API, newest first, with what changed (GET /v1/apis/:slug/changelog). */
74
+ changelog(slug) {
75
+ return this.send("GET", `/v1/apis/${encodeURIComponent(slug)}/changelog`);
76
+ }
77
+ /** Ask for one endpoint on a public API, or dry-run the ask (POST /v1/me/apis/:slug/endpoint-requests). */
78
+ askEndpoint(slug, ask) {
79
+ return this.send("POST", `/v1/me/apis/${encodeURIComponent(slug)}/endpoint-requests`, ask);
80
+ }
81
+ /** Report an endpoint that answers wrongly (POST /v1/me/apis/:slug/endpoint-reports). */
82
+ reportEndpoint(slug, report) {
83
+ return this.send("POST", `/v1/me/apis/${encodeURIComponent(slug)}/endpoint-reports`, report);
84
+ }
85
+ /** The key owner's reports and where each stands (GET /v1/me/endpoint-reports). */
86
+ listReports() {
87
+ return this.send("GET", "/v1/me/endpoint-reports");
88
+ }
89
+ /** The key owner's requests (GET /v1/me/requests). */
90
+ listRequests(filter) {
91
+ return this.send("GET", `/v1/me/requests${buildQuery(filter)}`);
92
+ }
93
+ /** Where a request is; `wait` holds the call until `state` no longer matches (GET /v1/me/requests/:id/status). */
94
+ requestStatus(id, wait = 0, state) {
95
+ const query = buildQuery({ ...(wait > 0 && { wait }), ...(wait > 0 && state && { state }) });
96
+ return this.send("GET", `/v1/me/requests/${encodeURIComponent(id)}/status${query}`);
97
+ }
98
+ /** Say something to the build of a request (POST /v1/me/requests/:id/messages). */
99
+ sendRequestMessage(id, text) {
100
+ return this.send("POST", `/v1/me/requests/${encodeURIComponent(id)}/messages`, { text });
101
+ }
102
+ /** Release every endpoint of a request that passed (POST /v1/me/requests/:id/publish). */
103
+ publishRequest(id) {
104
+ return this.send("POST", `/v1/me/requests/${encodeURIComponent(id)}/publish`, {});
105
+ }
106
+ /** Stop the build running for a request (POST /v1/me/requests/:id/cancel). */
107
+ cancelRequest(id) {
108
+ return this.send("POST", `/v1/me/requests/${encodeURIComponent(id)}/cancel`, {});
109
+ }
110
+ /** Call an endpoint of a draft before it is published (GET /v1/drafts/:draftId/<path>). */
111
+ callDraft(draftId, path, params) {
112
+ const filled = fillPath(path, params);
113
+ return this.send("GET", `/v1/drafts/${encodeURIComponent(draftId)}${filled.path}${buildQuery(filled.query)}`);
114
+ }
115
+ /** What this key is and may do (GET /v1/me/key). */
116
+ keyInfo() {
117
+ return this.send("GET", "/v1/me/key");
59
118
  }
60
119
  /** 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}` };
120
+ async send(method, path, json, extraHeaders = {}) {
121
+ const headers = { Authorization: `Bearer ${this.config.apiKey}`, ...extraHeaders };
63
122
  if (json !== undefined)
64
123
  headers["Content-Type"] = "application/json";
65
124
  const res = await this.request(`${this.config.baseUrl}${path}`, CALL_TIMEOUT_MS, {
package/dist/config.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = "0.1.1";
1
+ export const VERSION = "0.2.0";
2
2
  export const DEFAULT_BASE_URL = "https://api.maviapi.com";
3
3
  export const SITE_URL = "https://maviapi.com";
4
4
  /**
@@ -0,0 +1,667 @@
1
+ import { findEndpoint, truncate } from "./catalog.js";
2
+ import { siteLink } from "./config.js";
3
+ import { MAX_RESULT_CHARS, UserError, failure, humanDuration, objectArg, stringArg, text } from "./result.js";
4
+ /**
5
+ * The request tools: ask for an endpoint on an API that exists, follow its
6
+ * build, try the draft, publish it, cancel it. They drive the same routes the
7
+ * maviapi dashboard does, with the user's own API key. Every rule (who may
8
+ * publish, one build per API, the daily limits) is the backend's; these tools
9
+ * only word its answers for an agent.
10
+ */
11
+ /** Longest one-sentence summary the backend keeps for an endpoint. */
12
+ const SUMMARY_MAX = 300;
13
+ /** Longest a status tool call waits, under the tool timeouts MCP clients use. */
14
+ export const MAX_WAIT_SECONDS = 50;
15
+ /** Longest one status request is held by the backend. */
16
+ const SERVER_WAIT_SECONDS = 30;
17
+ const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
18
+ const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
19
+ export const REQUEST_TOOLS = [
20
+ {
21
+ name: "request_endpoint",
22
+ title: "Ask for a new maviapi endpoint",
23
+ description: "Add one endpoint to an API that already exists, or a changed version of one of its endpoints. " +
24
+ "Use it when get_api shows the API lacks the data, or an endpoint returns the wrong thing. " +
25
+ "Existing endpoints never change: a change ships as a new endpoint beside the old one (e.g. /search-v2). " +
26
+ "Without `confirm` nothing is built: the tool answers with the endpoint as it would be built, for the user to agree to. " +
27
+ "Call it again with the same arguments and `confirm: true` to start the build (about half an hour). " +
28
+ "One build of an API runs at a time: a request made while another is building waits in line and starts on its own. " +
29
+ "Needs an API key with the requests:write permission. Follow the build with get_build_status.",
30
+ inputSchema: {
31
+ type: "object",
32
+ properties: {
33
+ api: { type: "string", description: 'API slug (e.g. "booking") or the site\'s domain.' },
34
+ description: {
35
+ type: "string",
36
+ description: "What the endpoint returns, as specific as you can: the page it reads, the fields per record, the parameters. " +
37
+ 'E.g. "The reviews of one hotel, newest first: author, rating, date, text. Parameter: hotel id."',
38
+ },
39
+ path: {
40
+ type: "string",
41
+ description: 'For a new endpoint: its path, lowercase with dashes, no parameters in it. E.g. "/reviews" or "/hotel-photos".',
42
+ },
43
+ change: {
44
+ type: "string",
45
+ description: 'For a changed version of an existing endpoint: that endpoint\'s name or path, e.g. "/search". Use instead of `path`.',
46
+ },
47
+ confirm: { type: "boolean", description: "true starts the build. Leave it out to preview first." },
48
+ },
49
+ required: ["api", "description"],
50
+ },
51
+ annotations: WRITE,
52
+ },
53
+ {
54
+ name: "list_requests",
55
+ title: "List my maviapi requests",
56
+ description: "The API and endpoint requests made with this account, newest first, with their status. " +
57
+ "Filter by `api` (slug) or `status` (queued, building, deploying, published, failed). Needs an API key with a request permission.",
58
+ inputSchema: {
59
+ type: "object",
60
+ properties: {
61
+ api: { type: "string", description: "Only requests for this API slug." },
62
+ status: { type: "string", description: "Only requests in this status." },
63
+ },
64
+ },
65
+ annotations: READ,
66
+ },
67
+ {
68
+ name: "send_request_message",
69
+ title: "Message a maviapi build",
70
+ description: "Say something to the build of a request, in plain words: add detail, ask it to fix or drop an endpoint that failed, " +
71
+ 'or to try again after a failure (e.g. "fix /reviews", "also return the review date", "try again"). ' +
72
+ "Returns the build's answer. Needs an API key with the requests:write permission.",
73
+ inputSchema: {
74
+ type: "object",
75
+ properties: {
76
+ request_id: { type: "string", description: "The request_id from request_endpoint or create_api." },
77
+ message: { type: "string", description: "What to tell the build." },
78
+ },
79
+ required: ["request_id", "message"],
80
+ },
81
+ annotations: WRITE,
82
+ },
83
+ {
84
+ name: "call_draft",
85
+ title: "Call a draft maviapi endpoint",
86
+ description: "Call an endpoint of a request's draft before it is published, to check it returns the right data. " +
87
+ "Only endpoints get_build_status shows as ready answer. Draft calls cost no credits. Needs an API key with a request permission.",
88
+ inputSchema: {
89
+ type: "object",
90
+ properties: {
91
+ request_id: { type: "string", description: "The request_id from request_endpoint or create_api." },
92
+ endpoint: { type: "string", description: 'The endpoint path as get_build_status lists it, e.g. "/reviews".' },
93
+ params: { type: "object", description: "Endpoint parameters, path parameters included.", additionalProperties: true },
94
+ },
95
+ required: ["request_id", "endpoint"],
96
+ },
97
+ annotations: { ...READ, idempotentHint: false, openWorldHint: true },
98
+ },
99
+ {
100
+ name: "publish_request",
101
+ title: "Publish a maviapi request",
102
+ description: "Make a finished request live: every endpoint that passed its checks becomes part of the public API. " +
103
+ "Publishing changes what everyone who calls the API gets, so do it only when the user asked for it. " +
104
+ "Works once get_build_status says the request is ready. Needs an API key with the requests:publish permission.",
105
+ inputSchema: {
106
+ type: "object",
107
+ properties: {
108
+ request_id: { type: "string", description: "The request_id from request_endpoint or create_api." },
109
+ },
110
+ required: ["request_id"],
111
+ },
112
+ annotations: { ...WRITE, idempotentHint: true },
113
+ },
114
+ {
115
+ name: "cancel_request",
116
+ title: "Cancel a maviapi build",
117
+ description: "Stop the build that is running for a request. What was built before stays as it was. Needs an API key with the requests:write permission.",
118
+ inputSchema: {
119
+ type: "object",
120
+ properties: {
121
+ request_id: { type: "string", description: "The request_id from request_endpoint or create_api." },
122
+ },
123
+ required: ["request_id"],
124
+ },
125
+ annotations: { ...WRITE, destructiveHint: true, idempotentHint: true },
126
+ },
127
+ {
128
+ name: "report_endpoint_issue",
129
+ title: "Report a broken maviapi endpoint",
130
+ description: "Tell maviapi that an endpoint that exists returns the wrong thing: it fails, comes back empty, or repeats the same page. " +
131
+ "Use this instead of asking for a changed version when the endpoint is simply broken: the fix lands on the endpoint itself, for everyone. " +
132
+ "maviapi replays the call at once and then runs its own check of the endpoint. If that check fails too the report is confirmed and the endpoint is queued for repair; " +
133
+ "if not (a fault only certain parameters show, a repeated page, wrong values) a person on the team reads the report. " +
134
+ "A report's status is confirmed, fixed or received. " +
135
+ "Report what you saw: maviapi takes a report of an API only from an account that has called it with its own key, so make the failing call with call_api first, then pass its `params` here. " +
136
+ "Without `endpoint` and `description` it lists the reports made with this key. " +
137
+ "Needs an API key with the requests:write permission (any request permission to list).",
138
+ inputSchema: {
139
+ type: "object",
140
+ properties: {
141
+ api: { type: "string", description: 'API slug (e.g. "booking") or the site\'s domain.' },
142
+ endpoint: { type: "string", description: 'The endpoint\'s name or path, e.g. "/restaurants".' },
143
+ description: {
144
+ type: "string",
145
+ description: 'What is wrong, in a sentence or two: what you asked for, what came back, what you expected. E.g. "page=2 returns the same 30 restaurants as page 1."',
146
+ },
147
+ params: {
148
+ type: "object",
149
+ description: 'The parameters of a call that shows the fault, e.g. {"geo": "187147", "page": 2}.',
150
+ additionalProperties: true,
151
+ },
152
+ },
153
+ },
154
+ annotations: WRITE,
155
+ },
156
+ {
157
+ name: "get_key_info",
158
+ title: "Show this maviapi key",
159
+ description: "What the configured API key may do: its permissions, the account's plan and remaining credits, and the limits that apply. " +
160
+ "Check it before starting something that needs a permission or uses credits. Needs an API key with a request permission.",
161
+ inputSchema: { type: "object", properties: {} },
162
+ annotations: READ,
163
+ },
164
+ {
165
+ name: "get_changelog",
166
+ title: "Show a maviapi API's versions",
167
+ description: "Every version of an API, newest first: which is live, when it was built, and what changed (endpoints added or removed, fields changed). " +
168
+ "Use it when an endpoint behaves differently than before, or to pick a version for call_api's `version`.",
169
+ inputSchema: {
170
+ type: "object",
171
+ properties: {
172
+ api: { type: "string", description: 'API slug (e.g. "booking") or the site\'s domain.' },
173
+ },
174
+ required: ["api"],
175
+ },
176
+ annotations: READ,
177
+ },
178
+ ];
179
+ const NAMES = new Set(REQUEST_TOOLS.map((t) => t.name));
180
+ /** Where a report stands, in the API's own sentence when it sent one. */
181
+ function describeReport(report) {
182
+ if (typeof report.message === "string" && report.message)
183
+ return report.message;
184
+ return `status ${String(report.status ?? "unknown")}`;
185
+ }
186
+ const RUNNING = new Set(["queued", "reading", "mapping", "building", "testing"]);
187
+ /** Phases that change on their own, so waiting on them is worth it. */
188
+ const MOVING = new Set([...RUNNING, "publishing"]);
189
+ const payloadOf = (result) => result.body && typeof result.body === "object" ? result.body : {};
190
+ /** An endpoint path as callers write it: "/reviews", whatever prefix or case it came with. */
191
+ export function shortPath(path, slug) {
192
+ const prefix = slug ? `/v1/sites/${slug}` : "";
193
+ const tail = prefix && path.startsWith(prefix) ? path.slice(prefix.length) : path;
194
+ return tail.startsWith("/") ? tail : `/${tail}`;
195
+ }
196
+ /** What a request is for, in a few words. */
197
+ function subject(s) {
198
+ if (s.asked) {
199
+ return s.asked.of
200
+ ? `a changed GET ${s.asked.of} as GET ${s.asked.path} on ${s.slug}`
201
+ : `new endpoint GET ${s.asked.path} on ${s.slug}`;
202
+ }
203
+ return `an API for ${s.domain}`;
204
+ }
205
+ /** One version's changes as a sentence. */
206
+ export function describeDiff(diff) {
207
+ if (!diff || typeof diff !== "object")
208
+ return "";
209
+ const d = diff;
210
+ const list = (items, show) => (items ?? []).map((i) => show(i)).join(", ");
211
+ const parts = [];
212
+ if (d.added_endpoints?.length)
213
+ parts.push(`added ${list(d.added_endpoints, (p) => p)}`);
214
+ if (d.removed_endpoints?.length)
215
+ parts.push(`removed ${list(d.removed_endpoints, (p) => p)}`);
216
+ if (d.removed_fields?.length) {
217
+ parts.push(`fields removed: ${list(d.removed_fields, (f) => `${f.endpoint} ${f.path}`)}`);
218
+ }
219
+ if (d.retyped_fields?.length) {
220
+ parts.push(`fields changed type: ${list(d.retyped_fields, (f) => `${f.endpoint} ${f.path} (${f.from} to ${f.to})`)}`);
221
+ }
222
+ if (d.new_required_params?.length) {
223
+ parts.push(`new required parameters: ${list(d.new_required_params, (p) => `${p.endpoint} ${p.param}`)}`);
224
+ }
225
+ return parts.join("; ");
226
+ }
227
+ export class RequestTools {
228
+ client;
229
+ config;
230
+ deps;
231
+ /** What each request looked like last: its state token is passed back so a wait returns on the next change. */
232
+ states = new Map();
233
+ constructor(client, config, deps) {
234
+ this.client = client;
235
+ this.config = config;
236
+ this.deps = deps;
237
+ }
238
+ handles(name) {
239
+ return NAMES.has(name);
240
+ }
241
+ /** True when the rich status route can be used: it needs the user's own key. */
242
+ get available() {
243
+ return !this.config.usingPlaygroundKey;
244
+ }
245
+ call(name, args) {
246
+ if (name === "get_changelog")
247
+ return this.getChangelog(args);
248
+ this.requireOwnKey();
249
+ switch (name) {
250
+ case "request_endpoint":
251
+ return this.requestEndpoint(args);
252
+ case "list_requests":
253
+ return this.listRequests(args);
254
+ case "send_request_message":
255
+ return this.sendMessage(args);
256
+ case "call_draft":
257
+ return this.callDraft(args);
258
+ case "publish_request":
259
+ return this.publish(args);
260
+ case "cancel_request":
261
+ return this.cancel(args);
262
+ case "report_endpoint_issue":
263
+ return this.reportIssue(args);
264
+ case "get_key_info":
265
+ return this.keyInfo();
266
+ }
267
+ throw new UserError(`Unknown tool "${name}".`);
268
+ }
269
+ requireOwnKey() {
270
+ if (this.available)
271
+ return;
272
+ throw new UserError("This needs your own maviapi API key: the shared demo key cannot manage requests. " +
273
+ `Create a free key at ${siteLink("/sign-up", "request_tools")} and set MAVIAPI_API_KEY in this server's config.`);
274
+ }
275
+ /** The wording for a refusal of a request route; falls back to the generic one. */
276
+ refusal(result) {
277
+ const body = payloadOf(result);
278
+ const message = typeof body.message === "string" ? body.message : "";
279
+ if (result.status === 403 && body.error === "missing_scope") {
280
+ if (body.scope === "requests:publish") {
281
+ return ("This API key may not publish (it has no requests:publish permission). " +
282
+ `The user can publish from ${siteLink("/dashboard/requests", "missing_scope")}, or create a key with "Publish builds" turned on at ` +
283
+ `${siteLink("/dashboard/keys", "missing_scope")} and set it as MAVIAPI_API_KEY.`);
284
+ }
285
+ return ("This API key only calls data APIs: it has no request permissions (requests:write). " +
286
+ `The user can create a key with "Start and manage builds" turned on at ${siteLink("/dashboard/keys", "missing_scope")} ` +
287
+ "and set it as MAVIAPI_API_KEY in this server's config.");
288
+ }
289
+ if (result.status === 403 && body.error === "session_required") {
290
+ return "This maviapi deployment does not open that route to API keys.";
291
+ }
292
+ if (result.status === 429 && body.error !== "rate_limited") {
293
+ const said = message || "This account has started as many builds as it may for now.";
294
+ if (!result.retryAfter)
295
+ return said;
296
+ // The backend ends its sentence with "Try again later.": say when instead.
297
+ return `${said.replace(/\s*Try again later\.?\s*$/i, "")} Try again in ${humanDuration(result.retryAfter)}.`;
298
+ }
299
+ if ((result.status === 400 || result.status === 409 || result.status === 422) && message)
300
+ return message;
301
+ return this.deps.describeFailure(result);
302
+ }
303
+ async requestEndpoint(args) {
304
+ const api = await this.deps.resolveApi(stringArg(args, "api", true));
305
+ const description = stringArg(args, "description", true);
306
+ const path = stringArg(args, "path");
307
+ const change = stringArg(args, "change");
308
+ if (!path && !change) {
309
+ throw new UserError('Pass `path` for a new endpoint (e.g. "/reviews"), or `change` with an existing endpoint to get a changed version of it.');
310
+ }
311
+ if (path && change)
312
+ throw new UserError("Pass `path` or `change`, not both.");
313
+ const ask = { summary: truncate(description, SUMMARY_MAX) };
314
+ // The whole description reaches the build even when the summary cut it.
315
+ if (description.length > SUMMARY_MAX)
316
+ ask.messages = [{ role: "user", content: description }];
317
+ if (change) {
318
+ const endpoints = await this.client.listEndpoints(api.slug);
319
+ const existing = findEndpoint(endpoints, change);
320
+ if (!existing) {
321
+ throw new UserError(`${api.slug} has no endpoint "${change}" to change. Its endpoints: ${endpoints.map((e) => e.path).join(", ")}. ` +
322
+ "For a new endpoint pass `path` instead.");
323
+ }
324
+ ask.of = existing.path.toLowerCase();
325
+ }
326
+ else {
327
+ ask.path = `/${path.toLowerCase().replace(/^\/+/, "")}`;
328
+ }
329
+ const confirmed = args.confirm === true;
330
+ const result = await this.client.askEndpoint(api.slug, confirmed ? ask : { ...ask, dryRun: true });
331
+ const body = payloadOf(result);
332
+ if (!result.ok) {
333
+ if (result.status === 409 && body.error === "extension_in_progress") {
334
+ const own = typeof body.requestId === "string" ? ` It is your own request: ${body.requestId}.` : "";
335
+ return failure(`${String(body.message ?? "The line of requests for this API is full.")}${own} ` +
336
+ "An API holds 3 requests at a time, so ask again once one has finished (builds take about half an hour).");
337
+ }
338
+ return failure(this.refusal(result));
339
+ }
340
+ if (!confirmed) {
341
+ const endpoint = (body.endpoint ?? {});
342
+ const out = [
343
+ `Nothing has been built yet. This would add to ${api.name} (${api.slug}):`,
344
+ ` GET ${endpoint.path}${endpoint.of ? ` (a changed version of GET ${endpoint.of}, which stays as it is)` : ""}`,
345
+ ` ${endpoint.summary}`,
346
+ "",
347
+ "Show this to the user. If they agree, call request_endpoint again with the same arguments and confirm: true.",
348
+ "A build takes about half an hour; an account can start 2 an hour and 5 a day.",
349
+ ];
350
+ if (body.accepted === false) {
351
+ out.push("", "Note: the line of requests for this API is full (3 at a time), so this one would be refused right now. Ask again once one of them has finished.");
352
+ }
353
+ else if (body.building) {
354
+ const ahead = typeof body.ahead === "number" && body.ahead > 1 ? ` and ${body.ahead - 1} more ahead of it` : "";
355
+ out.push("", `Note: GET ${String(body.building).replace(/^GET /, "")} is being built for this API right now${ahead}. ` +
356
+ "One build runs at a time, so this one would wait in line and start on its own when they have finished.");
357
+ }
358
+ return text(out.join("\n"));
359
+ }
360
+ const id = String(body.id ?? "");
361
+ const built = (body.extension ?? {});
362
+ const waitingFor = typeof body.waitingFor === "string" ? body.waitingFor : null;
363
+ return text([
364
+ waitingFor
365
+ ? `Request accepted: GET ${built.path ?? ask.path ?? ""} on ${api.slug}. It waits in line behind GET ${waitingFor.replace(/^GET /, "")} and starts building on its own when that has finished.`
366
+ : `Build started: GET ${built.path ?? ask.path ?? ""} on ${api.slug}.`,
367
+ `request_id: ${id}`,
368
+ `status: ${String(body.status ?? "queued")}`,
369
+ "",
370
+ `Follow it with get_build_status {"request_id": "${id}", "wait_seconds": ${MAX_WAIT_SECONDS}}: it returns as soon as something changes.`,
371
+ "When it is ready, try it with call_draft, then publish_request makes it live.",
372
+ ].join("\n"));
373
+ }
374
+ async reportIssue(args) {
375
+ const endpointArg = stringArg(args, "endpoint");
376
+ const description = stringArg(args, "description");
377
+ if (!endpointArg && !description)
378
+ return this.listReports();
379
+ const api = await this.deps.resolveApi(stringArg(args, "api", true));
380
+ if (!endpointArg || !description) {
381
+ throw new UserError("Pass both `endpoint` (which one) and `description` (what is wrong).");
382
+ }
383
+ const endpoints = await this.client.listEndpoints(api.slug);
384
+ const endpoint = findEndpoint(endpoints, endpointArg);
385
+ if (!endpoint) {
386
+ throw new UserError(`${api.slug} has no endpoint "${endpointArg}". Its endpoints: ${endpoints.map((e) => e.path).join(", ")}.`);
387
+ }
388
+ const params = objectArg(args, "params");
389
+ const result = await this.client.reportEndpoint(api.slug, {
390
+ path: endpoint.path,
391
+ description,
392
+ ...(Object.keys(params).length > 0 && { params }),
393
+ });
394
+ const body = payloadOf(result);
395
+ if (!result.ok) {
396
+ if (result.status === 409 && body.error === "already_reported") {
397
+ return failure(`${String(body.message ?? "You already reported this endpoint today.")} ` +
398
+ "Call report_endpoint_issue with no arguments to see where that report stands.");
399
+ }
400
+ if (result.status === 403 && body.error === "not_a_caller") {
401
+ return failure(`maviapi takes a report of ${api.slug} only from an account that has called it with its own key. ` +
402
+ `Make the call that shows the fault with call_api {"api": "${api.slug}", ...} first, then report it again with the same params.`);
403
+ }
404
+ return failure(this.refusal(result));
405
+ }
406
+ return text([
407
+ `Report ${String(body.id ?? "")} on GET ${endpoint.path} of ${api.slug}: ${describeReport(body)}`,
408
+ ...(typeof body.found === "string" ? [`What maviapi saw: ${body.found}`] : []),
409
+ "",
410
+ body.status === "confirmed"
411
+ ? "Nothing more to do: the endpoint keeps its path, so the same call works once it is repaired. " +
412
+ "get_api shows the endpoint's health; report_endpoint_issue with no arguments shows where this report stands."
413
+ : "If the fault only shows with certain parameters, they are in the report for the person who reads it. " +
414
+ "If you need different behavior rather than a fix, request_endpoint with `change` builds a new version beside this one.",
415
+ ].join("\n"));
416
+ }
417
+ async listReports() {
418
+ const result = await this.client.listReports();
419
+ if (!result.ok)
420
+ return failure(this.refusal(result));
421
+ const rows = (Array.isArray(payloadOf(result).reports) ? payloadOf(result).reports : []);
422
+ if (rows.length === 0)
423
+ return text("No endpoint has been reported with this key's account.");
424
+ return text(rows
425
+ .map((r) => `${String(r.id)} ${String(r.slug)} GET ${String(r.path)} ${String(r.status)}\n ${describeReport(r)}`)
426
+ .join("\n"));
427
+ }
428
+ async listRequests(args) {
429
+ const api = stringArg(args, "api");
430
+ const status = stringArg(args, "status");
431
+ const slug = api ? (await this.deps.resolveApi(api)).slug : undefined;
432
+ const result = await this.client.listRequests({ ...(slug && { slug }), ...(status && { status }) });
433
+ if (!result.ok)
434
+ return failure(this.refusal(result));
435
+ const rows = (Array.isArray(result.body) ? result.body : []);
436
+ if (!rows.length) {
437
+ return text(`No requests${slug ? ` for ${slug}` : ""}${status ? ` with status ${status}` : ""} on this account. ` +
438
+ "request_endpoint adds an endpoint to an API; create_api builds an API for a new site.");
439
+ }
440
+ const lines = rows.slice(0, 50).map((r) => {
441
+ const what = r.extension ? `GET ${r.extension.path} on ${r.slug}` : `API for ${r.domain}${r.slug ? ` (${r.slug})` : ""}`;
442
+ // A finished build is not public until someone publishes it.
443
+ const state = r.status === "published" ? (r.live ? "built, API is public" : "built, not published") : r.status;
444
+ return `- ${r.id}: ${what}: ${state}${r.createdAt ? ` (${r.createdAt.slice(0, 10)})` : ""}`;
445
+ });
446
+ const more = rows.length > 50 ? [`(${rows.length - 50} older requests not shown)`] : [];
447
+ return text([`${rows.length} request(s):`, ...lines, ...more, "", "get_build_status with a request_id shows one in detail."].join("\n"));
448
+ }
449
+ /**
450
+ * The rich status of a request, waiting up to `waitSeconds` for a change.
451
+ * Returns null when this deployment (or this key) has no such route, so the
452
+ * caller can fall back to the plain build status.
453
+ */
454
+ async status(id, waitSeconds) {
455
+ const deadline = Date.now() + waitSeconds * 1000;
456
+ for (;;) {
457
+ const known = this.states.get(id);
458
+ const left = Math.max(0, Math.floor((deadline - Date.now()) / 1000));
459
+ // Wait only for a request that was last seen moving: a first look and a
460
+ // settled request are answered at once.
461
+ const wait = known && MOVING.has(known.phase) ? Math.min(left, SERVER_WAIT_SECONDS) : 0;
462
+ const asked = Date.now();
463
+ const result = await this.client.requestStatus(id, wait, known?.state);
464
+ if (!result.ok)
465
+ return { result, status: null };
466
+ const status = result.body;
467
+ this.states.set(id, { state: status.state, phase: status.phase });
468
+ const changed = !known || status.state !== known.state;
469
+ if (changed || wait === 0 || deadline - Date.now() < 2000)
470
+ return { result, status };
471
+ // A backend that answered without holding the call: do not spin on it.
472
+ if (Date.now() - asked < 1000)
473
+ await new Promise((r) => setTimeout(r, 2000));
474
+ }
475
+ }
476
+ /** A request's status as text an agent can act on. */
477
+ describeStatus(s) {
478
+ const out = [`Request ${s.id} (${subject(s)}): ${s.phase}.`];
479
+ const endpoints = (s.endpoints ?? []).filter((e) => e.status !== "dropped");
480
+ if (endpoints.length) {
481
+ out.push("", "Endpoints:");
482
+ for (const e of endpoints) {
483
+ const params = (e.params ?? []).map((p) => `${p.name}${p.example ? `=${p.example}` : ""}`).join(", ");
484
+ let line = `- ${e.method} ${shortPath(e.path, s.slug)}: ${e.status}`;
485
+ if (e.checks)
486
+ line += ` (${e.checks.summary}, ${e.checks.schemaFields} fields, ${e.checks.avgMs} ms)`;
487
+ if (e.failure)
488
+ line += `. ${e.failure.title}: ${e.failure.body}`;
489
+ if (params && e.status === "ready")
490
+ line += `. Parameters: ${params}`;
491
+ out.push(line);
492
+ }
493
+ }
494
+ const said = (s.messages ?? []).slice(-3).map((m) => `- ${m.text}${m.code ? ` ${m.code}` : ""}`);
495
+ if (said.length)
496
+ out.push("", "Latest from the build:", ...said);
497
+ out.push("");
498
+ const again = `get_build_status {"request_id": "${s.id}", "wait_seconds": ${MAX_WAIT_SECONDS}}`;
499
+ if (s.phase === "queued") {
500
+ out.push(`Waiting for a free build slot. Check again with ${again}.`);
501
+ }
502
+ else if (RUNNING.has(s.phase)) {
503
+ out.push(`Still working. Check again with ${again}: it returns as soon as something changes.`);
504
+ }
505
+ else if (s.phase === "paused") {
506
+ out.push('The site is rate limiting the build. send_request_message "continue slowly" or "retry" tells it how to go on.');
507
+ }
508
+ else if (s.phase === "ready") {
509
+ out.push("Built and tested, not public yet. Try an endpoint with call_draft. " +
510
+ "When the user wants it live, publish_request publishes it " +
511
+ `(or they can at ${siteLink(`/apis/request/${s.id}`, "request_ready")}).`);
512
+ }
513
+ else if (s.phase === "publishing") {
514
+ out.push(`Going live now, usually under a minute. Check again with ${again}.`);
515
+ }
516
+ else if (s.phase === "published") {
517
+ out.push(`Live${s.live ? ` as ${s.live.version} at ${s.live.baseUrl}` : ""}. get_api "${s.slug}" shows it and call_api calls it.`);
518
+ }
519
+ else if (s.phase === "failed") {
520
+ out.push(`The build stopped: ${s.error ?? "no reason given"}. ` +
521
+ 'send_request_message "try again" builds it again; a narrower description may build where this did not.');
522
+ }
523
+ else {
524
+ out.push("Nothing passed, so there is nothing to publish. The failures are above; " +
525
+ 'send_request_message can ask for a fix, e.g. "fix /reviews".');
526
+ }
527
+ return out.join("\n");
528
+ }
529
+ async loadStatus(id) {
530
+ const result = await this.client.requestStatus(id);
531
+ if (result.status === 404) {
532
+ throw new UserError(`No request "${id}" on this account. list_requests shows the ones there are.`);
533
+ }
534
+ if (!result.ok)
535
+ throw new UserError(this.refusal(result));
536
+ const status = result.body;
537
+ this.states.set(id, { state: status.state, phase: status.phase });
538
+ return status;
539
+ }
540
+ async sendMessage(args) {
541
+ const id = stringArg(args, "request_id", true);
542
+ const message = stringArg(args, "message", true);
543
+ const result = await this.client.sendRequestMessage(id, message);
544
+ if (result.status === 404) {
545
+ return failure(`No request "${id}" on this account. list_requests shows the ones there are.`);
546
+ }
547
+ // A refused change (409) still gets an answer in the build's own words.
548
+ if (!result.ok && result.status !== 409)
549
+ return failure(this.refusal(result));
550
+ const status = await this.loadStatus(id);
551
+ const reply = (status.messages ?? []).filter((m) => m.kind === "agent").at(-1);
552
+ const out = [reply ? `The build answered: ${reply.text}` : "Sent.", "", this.describeStatus(status)];
553
+ return result.ok ? text(out.join("\n")) : failure(out.join("\n"));
554
+ }
555
+ async callDraft(args) {
556
+ const id = stringArg(args, "request_id", true);
557
+ const ref = stringArg(args, "endpoint", true);
558
+ const params = objectArg(args, "params");
559
+ const status = await this.loadStatus(id);
560
+ const wanted = shortPath(ref.replace(/^GET\s+/i, ""), status.slug).toLowerCase();
561
+ const endpoints = (status.endpoints ?? []).filter((e) => e.status !== "dropped");
562
+ const endpoint = endpoints.find((e) => shortPath(e.path, status.slug).toLowerCase() === wanted);
563
+ if (!endpoint) {
564
+ throw new UserError(`This request has no endpoint "${ref}". It has: ${endpoints.map((e) => shortPath(e.path, status.slug)).join(", ") || "none yet"}.`);
565
+ }
566
+ if (endpoint.status !== "ready" || !status.draft) {
567
+ throw new UserError(`GET ${shortPath(endpoint.path, status.slug)} is ${endpoint.status}, so it cannot be called yet. ` +
568
+ "Only ready endpoints answer; get_build_status shows when it is.");
569
+ }
570
+ // The build's own example stands in for a parameter the caller left out.
571
+ const filled = { ...params };
572
+ for (const p of endpoint.params ?? []) {
573
+ if (p.in === "path" && filled[p.name] === undefined && p.example)
574
+ filled[p.name] = p.example;
575
+ }
576
+ const result = await this.client.callDraft(status.draft.id, shortPath(endpoint.path, status.slug), filled);
577
+ const body = typeof result.body === "string" ? result.body : JSON.stringify(result.body);
578
+ const out = truncate(body, MAX_RESULT_CHARS, "pass a smaller limit, or page with offset");
579
+ return result.ok
580
+ ? text(out)
581
+ : failure(`The draft answered ${result.status}: ${truncate(body, 2000)}`);
582
+ }
583
+ async publish(args) {
584
+ const id = stringArg(args, "request_id", true);
585
+ const result = await this.client.publishRequest(id);
586
+ if (result.status === 404) {
587
+ return failure(`No request "${id}" on this account. list_requests shows the ones there are.`);
588
+ }
589
+ if (result.ok) {
590
+ const version = String(payloadOf(result).version ?? "");
591
+ return text(`Publishing${version ? ` ${version}` : ""}. It goes live in under a minute. ` +
592
+ `Confirm with get_build_status {"request_id": "${id}", "wait_seconds": ${MAX_WAIT_SECONDS}}: the phase turns to published.`);
593
+ }
594
+ if (result.status === 409) {
595
+ // The reason is the build's last message; the code alone says little.
596
+ const status = await this.loadStatus(id);
597
+ const reply = (status.messages ?? []).filter((m) => m.kind === "agent").at(-1);
598
+ return failure(`Not published (${String(payloadOf(result).error ?? "refused")}). ${reply?.text ?? ""}\n\n${this.describeStatus(status)}`);
599
+ }
600
+ return failure(this.refusal(result));
601
+ }
602
+ async cancel(args) {
603
+ const id = stringArg(args, "request_id", true);
604
+ const result = await this.client.cancelRequest(id);
605
+ if (result.status === 404) {
606
+ return failure(`No request "${id}" on this account. list_requests shows the ones there are.`);
607
+ }
608
+ if (!result.ok)
609
+ return failure(this.refusal(result));
610
+ const status = result.body;
611
+ if (status.state)
612
+ this.states.set(id, { state: status.state, phase: status.phase });
613
+ return text(`Cancelled. ${this.describeStatus(status)}`);
614
+ }
615
+ async keyInfo() {
616
+ const result = await this.client.keyInfo();
617
+ if (!result.ok)
618
+ return failure(this.refusal(result));
619
+ const info = result.body;
620
+ const can = (scope) => info.key.scopes.includes(scope);
621
+ const rate = (r) => [r?.perHour && `${r.perHour} an hour`, r?.perDay && `${r.perDay} a day`].filter(Boolean).join(", ");
622
+ const out = [
623
+ `Key "${info.key.name}" (${info.key.prefix}, ${info.key.env}).`,
624
+ "It can call every API" +
625
+ (can("requests:write") ? ", start and manage builds" : "") +
626
+ (can("requests:publish") ? ", and publish them" : "") +
627
+ ".",
628
+ ];
629
+ if (!can("requests:write")) {
630
+ out.push("It cannot ask for endpoints or manage builds (no requests:write permission).");
631
+ }
632
+ if (!can("requests:publish")) {
633
+ out.push(`It cannot publish (no requests:publish permission): the user publishes at ${siteLink("/dashboard/requests", "key_info")}, or creates a key that may at ${siteLink("/dashboard/keys", "key_info")}.`);
634
+ }
635
+ out.push("", `Plan: ${info.plan.name}. Credits: ${info.credits.remaining} of ${info.credits.included} left` +
636
+ (info.credits.periodEnd ? ` until ${info.credits.periodEnd.slice(0, 10)}` : "") +
637
+ (info.credits.payAsYouGo ? " (calls past that are billed as you go)." : "."), `Limits: ${info.limits.callsPerMinute} calls a minute` +
638
+ (info.limits.callsPerDay ? `, ${info.limits.callsPerDay} a day (test key)` : "") +
639
+ `. Endpoint requests: ${rate(info.limits.endpointRequests) || "see the dashboard"}. New API builds: ${rate(info.limits.newApiBuilds) || "see the dashboard"}.`);
640
+ if (info.pins?.length) {
641
+ out.push(`Pinned versions: ${info.pins.map((p) => `${p.slug} on v${p.version}`).join(", ")}.`);
642
+ }
643
+ return text(out.join("\n"));
644
+ }
645
+ async getChangelog(args) {
646
+ const api = await this.deps.resolveApi(stringArg(args, "api", true));
647
+ const result = await this.client.changelog(api.slug);
648
+ if (!result.ok)
649
+ return failure(this.deps.describeFailure(result));
650
+ const entries = (result.body.entries ?? []);
651
+ if (!entries.length)
652
+ return text(`${api.name} (${api.slug}) has no recorded versions yet.`);
653
+ const lines = entries.slice(0, 30).map((e) => {
654
+ const tags = [e.state === "active" ? "live" : e.state, e.compat === "breaking" ? "breaking" : ""]
655
+ .filter(Boolean)
656
+ .join(", ");
657
+ const changes = e.hotfix_of ? `repair of v${e.hotfix_of}` : describeDiff(e.diff);
658
+ return `- v${e.version} (${tags}${e.date ? `, ${e.date.slice(0, 10)}` : ""})${changes ? `: ${changes}` : ""}`;
659
+ });
660
+ return text([
661
+ `${api.name} (${api.slug}) versions, newest first:`,
662
+ ...lines,
663
+ "",
664
+ 'call_api serves the live version; pass "version": <n> to call another one that is still callable.',
665
+ ].join("\n"));
666
+ }
667
+ }
package/dist/result.js ADDED
@@ -0,0 +1,51 @@
1
+ /** Cap on one tool result, so a large listing cannot swallow the agent's context. */
2
+ export const MAX_RESULT_CHARS = 50_000;
3
+ /** A failure worth showing the agent verbatim: bad input, unknown names. */
4
+ export class UserError extends Error {
5
+ }
6
+ export function text(body) {
7
+ return { content: [{ type: "text", text: body }] };
8
+ }
9
+ export function failure(body) {
10
+ return { content: [{ type: "text", text: body }], isError: true };
11
+ }
12
+ export function stringArg(args, name, required = false) {
13
+ const value = args[name];
14
+ if (typeof value === "string" && value.trim())
15
+ return value.trim();
16
+ if (value === undefined || value === null || value === "") {
17
+ if (required)
18
+ throw new UserError(`\`${name}\` is required.`);
19
+ return undefined;
20
+ }
21
+ throw new UserError(`\`${name}\` must be a string.`);
22
+ }
23
+ /** Models sometimes send `params` as a JSON string; accept that too. */
24
+ export function objectArg(args, name) {
25
+ let value = args[name];
26
+ if (value === undefined || value === null || value === "")
27
+ return {};
28
+ if (typeof value === "string") {
29
+ try {
30
+ value = JSON.parse(value);
31
+ }
32
+ catch {
33
+ throw new UserError(`\`${name}\` must be an object, e.g. {"q": "istanbul"}.`);
34
+ }
35
+ }
36
+ if (typeof value !== "object" || Array.isArray(value)) {
37
+ throw new UserError(`\`${name}\` must be an object, e.g. {"q": "istanbul"}.`);
38
+ }
39
+ return value;
40
+ }
41
+ /** "45 seconds", "30 minutes", "29 days": the largest unit that fits. */
42
+ export function humanDuration(seconds) {
43
+ const units = [["day", 86_400], ["hour", 3_600], ["minute", 60]];
44
+ for (const [unit, size] of units) {
45
+ if (seconds >= size) {
46
+ const n = Math.round(seconds / size);
47
+ return `${n} ${unit}${n === 1 ? "" : "s"}`;
48
+ }
49
+ }
50
+ return `${seconds} second${seconds === 1 ? "" : "s"}`;
51
+ }
package/dist/server.js CHANGED
@@ -5,7 +5,10 @@ import { VERSION } from "./config.js";
5
5
  import { Toolset } from "./tools.js";
6
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
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).`;
8
+ If no API covers the site you need, create_api builds one (about half an hour; follow it with get_build_status).
9
+ If an API exists but lacks an endpoint, or you need one to behave differently, request_endpoint adds one: preview it, let the user agree, start it with confirm: true, follow it with get_build_status (wait_seconds), try it with call_draft, and publish_request when the user wants it live.
10
+ If an endpoint is simply broken (it fails, comes back empty, or repeats the same page), report_endpoint_issue with the params of the failing call: maviapi replays it and checks the endpoint itself. A fault its own check confirms is repaired in place; the rest are read by a person.
11
+ Starting a build and publishing change things for the user: do them when the user asked, not on your own.`;
9
12
  /**
10
13
  * The tool list is computed at request time (MAVIAPI_TOOLS adds one typed tool
11
14
  * per endpoint, read from the live catalog), so the handlers are registered on
package/dist/tools.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { DEFAULT_LIMIT, MissingParamsError, describeParams, findApi, findEndpoint, hostOf, outlineOutput, searchApis, toolName, truncate, } from "./catalog.js";
2
2
  import { MaviapiError } from "./client.js";
3
+ import { MAX_WAIT_SECONDS, REQUEST_TOOLS, RequestTools } from "./requests.js";
4
+ import { MAX_RESULT_CHARS, UserError, failure, humanDuration, objectArg, stringArg, text } from "./result.js";
5
+ export { humanDuration };
3
6
  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
7
  const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true };
7
8
  const GENERIC_TOOLS = [
8
9
  {
@@ -22,8 +23,10 @@ const GENERIC_TOOLS = [
22
23
  {
23
24
  name: "get_api",
24
25
  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.",
26
+ description: "Show one maviapi API's endpoints: what each returns, its parameters (required ones marked), the fields in the response, " +
27
+ "and whether each endpoint is working right now. Also lists endpoints that are being built. " +
28
+ "Accepts the API slug from search_apis, or the site's domain (e.g. \"airbnb.com\"). Read this before call_api. " +
29
+ "If the API lacks what you need, request_endpoint adds an endpoint to it.",
27
30
  inputSchema: {
28
31
  type: "object",
29
32
  properties: {
@@ -49,6 +52,10 @@ const GENERIC_TOOLS = [
49
52
  description: "Endpoint parameters, as listed by get_api.",
50
53
  additionalProperties: true,
51
54
  },
55
+ version: {
56
+ type: "integer",
57
+ description: "Call this version of the API instead of the live one (see get_changelog). Rarely needed.",
58
+ },
52
59
  },
53
60
  required: ["api", "endpoint"],
54
61
  },
@@ -57,9 +64,9 @@ const GENERIC_TOOLS = [
57
64
  {
58
65
  name: "create_api",
59
66
  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. " +
67
+ description: "Start an API draft for a website that no catalog API covers. maviapi's build agent studies the site and builds " +
68
+ "a JSON API from a plain-language description. This returns a request_id at once; follow it with get_build_status. " +
69
+ "Build completion does not publish the API. Use your own account and key to review and publish the draft in the dashboard. " +
63
70
  `With the shared demo key each network gets ${PLAYGROUND_FREE_BUILDS} free builds per 30 days.`,
64
71
  inputSchema: {
65
72
  type: "object",
@@ -82,82 +89,43 @@ const GENERIC_TOOLS = [
82
89
  {
83
90
  name: "get_build_status",
84
91
  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.",
92
+ description: "Where a build started with create_api or request_endpoint is: its phase, each endpoint with its test results or what went wrong, " +
93
+ "and what the build said last. A finished build is not public until it is published (publish_request, or the owner in the dashboard). " +
94
+ `Pass \`wait_seconds\` (up to ${MAX_WAIT_SECONDS}) and the call returns as soon as something changes, so you can follow a build ` +
95
+ "without sleeping. With the shared demo key it reports the plain build status only.",
88
96
  inputSchema: {
89
97
  type: "object",
90
98
  properties: {
91
- request_id: { type: "string", description: "The request_id create_api returned." },
99
+ request_id: { type: "string", description: "The request_id create_api or request_endpoint returned." },
100
+ wait_seconds: {
101
+ type: "integer",
102
+ description: `Hold the call up to this many seconds (max ${MAX_WAIT_SECONDS}) until the build's state changes.`,
103
+ },
92
104
  },
93
105
  required: ["request_id"],
94
106
  },
95
107
  annotations: { ...READ_ONLY, idempotentHint: false, openWorldHint: false },
96
108
  },
97
109
  ];
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
110
  export class Toolset {
148
111
  client;
149
112
  config;
150
113
  log;
151
114
  dedicated = null;
152
115
  nudged = false;
116
+ requests;
153
117
  constructor(client, config = client.config, log = (m) => console.error(m)) {
154
118
  this.client = client;
155
119
  this.config = config;
156
120
  this.log = log;
121
+ this.requests = new RequestTools(client, config, {
122
+ resolveApi: (ref) => this.resolveApi(ref),
123
+ describeFailure: (result) => this.describeFailure(result),
124
+ });
157
125
  }
158
126
  async list() {
159
127
  const dedicated = await this.dedicatedTools();
160
- return [...GENERIC_TOOLS, ...[...dedicated.values()].map((d) => d.tool)];
128
+ return [...GENERIC_TOOLS, ...REQUEST_TOOLS, ...[...dedicated.values()].map((d) => d.tool)];
161
129
  }
162
130
  async call(name, args = {}) {
163
131
  try {
@@ -173,6 +141,8 @@ export class Toolset {
173
141
  case "get_build_status":
174
142
  return await this.getBuildStatus(args);
175
143
  }
144
+ if (this.requests.handles(name))
145
+ return await this.requests.call(name, args);
176
146
  const dedicated = (await this.dedicatedTools()).get(name);
177
147
  if (!dedicated)
178
148
  throw new UserError(`Unknown tool "${name}".`);
@@ -218,14 +188,30 @@ export class Toolset {
218
188
  }
219
189
  async getApi(args) {
220
190
  const api = await this.resolveApi(stringArg(args, "api", true));
221
- const endpoints = await this.client.listEndpoints(api.slug);
191
+ // Health and what is being built are extras: the listing stands without them.
192
+ const [endpoints, health, building] = await Promise.all([
193
+ this.client.listEndpoints(api.slug),
194
+ this.client.apiHealth(api.slug).catch(() => null),
195
+ this.client.buildingEndpoints(api.slug).catch(() => null),
196
+ ]);
197
+ const statusOf = new Map();
198
+ const healthBody = health?.ok ? health.body : null;
199
+ for (const e of healthBody?.endpoints ?? [])
200
+ statusOf.set(e.path.toLowerCase(), e.status);
222
201
  const out = [`# ${api.name} (${api.slug})`];
223
202
  if (api.target_url)
224
203
  out.push(`Site: ${api.target_url}`);
225
204
  if (api.description)
226
205
  out.push(api.description.trim());
206
+ if (healthBody?.status && healthBody.status !== "unknown")
207
+ out.push(`Health: ${healthBody.status}`);
227
208
  for (const ep of endpoints) {
228
209
  out.push("", `## ${ep.name}: ${ep.method} ${ep.path}`);
210
+ const status = statusOf.get(ep.path.toLowerCase());
211
+ // Only a problem is worth a line: most endpoints are fine.
212
+ if (status && status !== "operational" && status !== "unknown") {
213
+ out.push(`Status: ${status} right now. Calls may fail; maviapi repairs endpoints when a site changes.`);
214
+ }
229
215
  if (ep.description)
230
216
  out.push(ep.description);
231
217
  const params = describeParams(ep.inputSchema);
@@ -235,10 +221,17 @@ export class Toolset {
235
221
  if (fields.length)
236
222
  out.push("Returns:", ...fields.map((f) => ` ${f}`));
237
223
  }
224
+ const beingBuilt = building?.ok
225
+ ? (building.body.building ?? []).map((b) => `GET ${b.path}`)
226
+ : [];
227
+ if (beingBuilt.length) {
228
+ out.push("", `Being built right now: ${beingBuilt.join(", ")}. It appears here once it is published.`);
229
+ }
238
230
  const first = endpoints[0];
239
231
  if (first) {
240
232
  out.push("", `Call one with call_api, e.g. {"api": "${api.slug}", "endpoint": "${first.name}", "params": {…}}.`);
241
233
  }
234
+ out.push("Missing something? request_endpoint adds an endpoint to this API.");
242
235
  return text(truncate(out.join("\n"), MAX_RESULT_CHARS, "too many endpoints to show"));
243
236
  }
244
237
  async callApi(args) {
@@ -251,10 +244,14 @@ export class Toolset {
251
244
  throw new UserError(`${api.slug} has no endpoint "${ref}". Available: ${endpoints.map((e) => e.name).join(", ")}. ` +
252
245
  `get_api "${api.slug}" lists their parameters.`);
253
246
  }
254
- return this.run(api.slug, endpoint, params);
247
+ const version = args.version === undefined || args.version === null ? undefined : Number(args.version);
248
+ if (version !== undefined && (!Number.isInteger(version) || version < 1)) {
249
+ throw new UserError("`version` must be a version number from get_changelog, e.g. 3.");
250
+ }
251
+ return this.run(api.slug, endpoint, params, version);
255
252
  }
256
253
  /** Call an endpoint and turn the outcome into something an agent can act on. */
257
- async run(slug, endpoint, input) {
254
+ async run(slug, endpoint, input, version) {
258
255
  const params = { ...input };
259
256
  if ("limit" in endpoint.inputSchema.properties && params.limit === undefined) {
260
257
  params.limit = DEFAULT_LIMIT;
@@ -262,7 +259,7 @@ export class Toolset {
262
259
  const missing = (endpoint.inputSchema.required ?? []).filter((name) => params[name] === undefined || params[name] === null || params[name] === "");
263
260
  if (missing.length)
264
261
  throw new MissingParamsError(missing);
265
- const result = await this.client.call(slug, endpoint, params);
262
+ const result = await this.client.call(slug, endpoint, params, version);
266
263
  if (!result.ok)
267
264
  return failure(this.describeFailure(result));
268
265
  const body = typeof result.body === "string" ? result.body : JSON.stringify(result.body);
@@ -326,8 +323,8 @@ export class Toolset {
326
323
  `request_id: ${payload.id}`,
327
324
  `status: ${payload.status ?? "queued"}`,
328
325
  "",
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.",
326
+ "Check progress with get_build_status every few minutes. Build completion does not make the API public.",
327
+ this.publicationGuidance(),
331
328
  ];
332
329
  if (this.config.usingPlaygroundKey) {
333
330
  out.push("", `(Built with the shared demo key: each network gets ${PLAYGROUND_FREE_BUILDS} free builds per 30 days. ` +
@@ -348,6 +345,20 @@ export class Toolset {
348
345
  }
349
346
  async getBuildStatus(args) {
350
347
  const id = stringArg(args, "request_id", true);
348
+ // With the user's own key the request routes answer in full: endpoints,
349
+ // test results, what the build said, and a wait until something changes.
350
+ if (this.requests.available) {
351
+ const wait = Math.min(Math.max(Math.trunc(Number(args.wait_seconds)) || 0, 0), MAX_WAIT_SECONDS);
352
+ const rich = await this.requests.status(id, wait);
353
+ if (rich.status) {
354
+ if (rich.status.phase === "published" && rich.status.slug)
355
+ this.client.invalidateApi(rich.status.slug);
356
+ return text(this.requests.describeStatus(rich.status));
357
+ }
358
+ if (rich.result.status === 429)
359
+ return failure(this.describeFailure(rich.result));
360
+ // Anything else (an older deployment, a route closed to keys): the plain status below.
361
+ }
351
362
  const result = await this.client.getBuild(id);
352
363
  if (result.status === 404) {
353
364
  return failure(`No build "${id}" was started with this API key. Use the request_id create_api returned.`);
@@ -359,10 +370,23 @@ export class Toolset {
359
370
  const recent = (build.progress ?? []).slice(-3).map((p) => `- ${p.message}`);
360
371
  if (recent.length)
361
372
  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.`);
373
+ if (build.status === "published") {
374
+ out.push("", 'Build completed. The build status "published" does not confirm that this build is public.');
375
+ if (build.slug) {
376
+ // A first build stays private until owner publication. An existing
377
+ // public API can also have a new candidate that is not released yet.
378
+ this.client.invalidateCatalog();
379
+ try {
380
+ const listed = (await this.client.listApis()).some((api) => api.slug === build.slug);
381
+ out.push(listed
382
+ ? `API "${build.slug}" is in the public catalog. get_api and call_api use its current public build; this completed build may still await owner publication.`
383
+ : `API "${build.slug}" is not in the public catalog yet. Review and publish the draft before using get_api or call_api.`);
384
+ }
385
+ catch {
386
+ out.push(`Could not verify public catalog visibility for "${build.slug}". Do not assume the completed build is callable; check again later.`);
387
+ }
388
+ }
389
+ out.push(this.publicationGuidance());
366
390
  }
367
391
  else if (build.status === "failed") {
368
392
  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.`);
@@ -372,6 +396,13 @@ export class Toolset {
372
396
  }
373
397
  return text(out.join("\n"));
374
398
  }
399
+ publicationGuidance() {
400
+ return this.config.usingPlaygroundKey
401
+ ? "The shared demo key does not give you an owner dashboard session for this draft. " +
402
+ `To review and publish your own build, create an account at ${siteLink("/sign-up", "build_publication")} ` +
403
+ "and start the build with your personal MAVIAPI_API_KEY."
404
+ : `The owner can review and publish the draft at ${siteLink("/dashboard/requests", "build_publication")}.`;
405
+ }
375
406
  /** Typed per-endpoint tools for the APIs named in MAVIAPI_TOOLS. */
376
407
  dedicatedTools() {
377
408
  const wanted = this.config.dedicatedApis;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maviapi/mcp",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
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
5
  "mcpName": "io.github.kuzenlabs/maviapi-mcp",
6
6
  "type": "module",