desearch-mcp-server 0.1.4 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/README.md +209 -6
  3. package/build/http.d.ts +2 -8
  4. package/build/http.d.ts.map +1 -1
  5. package/build/http.js +126 -37
  6. package/build/oauth/client-ip.d.ts +10 -0
  7. package/build/oauth/client-ip.d.ts.map +1 -0
  8. package/build/oauth/client-ip.js +28 -0
  9. package/build/oauth/crypto.d.ts +20 -0
  10. package/build/oauth/crypto.d.ts.map +1 -0
  11. package/build/oauth/crypto.js +89 -0
  12. package/build/oauth/errors.d.ts +9 -0
  13. package/build/oauth/errors.d.ts.map +1 -0
  14. package/build/oauth/errors.js +13 -0
  15. package/build/oauth/flow.d.ts +8 -0
  16. package/build/oauth/flow.d.ts.map +1 -0
  17. package/build/oauth/flow.js +424 -0
  18. package/build/oauth/http.d.ts +24 -0
  19. package/build/oauth/http.d.ts.map +1 -0
  20. package/build/oauth/http.js +137 -0
  21. package/build/oauth/metadata.d.ts +19 -0
  22. package/build/oauth/metadata.d.ts.map +1 -0
  23. package/build/oauth/metadata.js +86 -0
  24. package/build/oauth/page.d.ts +14 -0
  25. package/build/oauth/page.d.ts.map +1 -0
  26. package/build/oauth/page.js +92 -0
  27. package/build/oauth/rate-limit.d.ts +14 -0
  28. package/build/oauth/rate-limit.d.ts.map +1 -0
  29. package/build/oauth/rate-limit.js +19 -0
  30. package/build/oauth/redirects.d.ts +14 -0
  31. package/build/oauth/redirects.d.ts.map +1 -0
  32. package/build/oauth/redirects.js +78 -0
  33. package/build/oauth/store.d.ts +139 -0
  34. package/build/oauth/store.d.ts.map +1 -0
  35. package/build/oauth/store.js +606 -0
  36. package/build/oauth/validate-key.d.ts +21 -0
  37. package/build/oauth/validate-key.d.ts.map +1 -0
  38. package/build/oauth/validate-key.js +61 -0
  39. package/build/people.d.ts +125 -0
  40. package/build/people.d.ts.map +1 -0
  41. package/build/people.js +402 -0
  42. package/build/request-key.d.ts +9 -0
  43. package/build/request-key.d.ts.map +1 -0
  44. package/build/request-key.js +24 -0
  45. package/build/server.d.ts +5 -4
  46. package/build/server.d.ts.map +1 -1
  47. package/build/server.js +404 -9
  48. package/package.json +32 -9
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ Remote MCP OAuth 2.1 and per-IP rate limits, on top of the 0.2.0 People Search tools. `search` and `fetch` are included for clients that look up a page by query and then read it.
6
+
7
+ - Protected resource metadata, authorization server metadata, dynamic client registration, authorization code with PKCE S256, and rotating refresh tokens. Refresh rotation is atomic. Replaying an authorization code revokes tokens already issued from that code.
8
+ - The sign-in page asks for a Desearch API key and checks it before issuing a code. Only HTTP 422 counts as a valid key. Access tokens are opaque. The key is encrypted at rest and is not placed in the token.
9
+ - A raw Desearch API key in `Authorization` or `x-api-key` still works. `tools/list` without a key still returns tools. `tools/call` without a key returns HTTP 401 with `WWW-Authenticate`, and the body is a tool error with `_meta["mcp/www_authenticate"]`.
10
+ - Production (`NODE_ENV=production` or `VERCEL`) requires `OAUTH_ISSUER` and `OAUTH_STORE=redis`. The issuer is not taken from forwarded host headers. Access tokens must match this server's resource. A bad or expired token challenge includes `error="invalid_token"`. `OAUTH_REQUIRE_AUTH_ON_INITIALIZE=true` makes keyless `initialize` return 401. The sign-in form rejects a cross-site `Origin` or `Referer`, and rejects a POST that sends none of those or `Sec-Fetch-Site`.
11
+ - `POST /register` allows 10 requests an hour per IP. The sign-in key check allows 20 requests every 10 minutes per IP. A request past the limit returns 429 with `Retry-After`.
12
+ - `search` takes `query` and returns titles and links. `fetch` takes a URL and returns the page text.
13
+ - Tool annotations are not all read-only. Lookup tools, including `search` and `fetch`, keep `readOnlyHint: true`, `destructiveHint: false`, and `openWorldHint: true`. `people-search` starts a billed job, so `readOnlyHint` is false and `destructiveHint` is false. `people-search-control` can cancel a search, so `readOnlyHint` is false and `destructiveHint` is true. `openWorldHint` is true on every tool.
14
+
15
+ ## 0.2.0
16
+
17
+ People Search tools. Release this version only after People Search is live on `api.desearch.ai`; until then the new tools return the API's HTTP error.
18
+
19
+ People Search finds X profiles, YouTube creators, LinkedIn members, or TikTok creators who match a plain-language description. desearch-js 1.5 has no People Search methods, so `people.ts` calls the `/desearch/people/*` routes directly with the same key header.
20
+
21
+ | Tool | Route | Billed |
22
+ | --- | --- | --- |
23
+ | `people-search` | `POST /desearch/people/search/{x,youtube,linkedin,tiktok}` | Yes. Reserves `count` people at the platform's per-person price and settles to the people delivered (minimum per search; nothing when it finds no one). |
24
+ | `people-search-status` | `GET /desearch/people/tasks/{id}` and `GET /desearch/people/tasks/{id}/results` | No |
25
+ | `people-search-control` | `POST /desearch/people/tasks/{id}/pause`, `/resume`, `/cancel` | No |
26
+ | `people-search-tasks` | `GET /desearch/people/tasks` | No |
27
+ | `people-profiles` | `GET /desearch/people/profiles` | No |
28
+
29
+ - `people-search` takes each platform's filters as top-level arguments and rejects a filter that does not apply to the chosen platform before the billed call. `idempotency_key` is sent as `Idempotency-Key`, so a retry returns the first task instead of starting a second search.
30
+ - `people-search-status` returns compact people (name, handle, url, platform, audience, location, score, why they matched, contacts, links) and a `next_cursor` that returns only people found since the previous call.
31
+ - Every people tool returns a `next` line that says what to call next.
32
+ - People tools reject unknown arguments, so a misspelled or nested filter is not dropped from a billed search.
33
+ - The `/export` CSV and JSON Lines routes are not tools.
34
+
35
+ ### Tool annotations
36
+
37
+ The 15 existing tools keep `readOnlyHint: true`, `destructiveHint: false`, `openWorldHint: true`. So do `people-search-status`, `people-search-tasks`, and `people-profiles`.
38
+
39
+ - `people-search`: `readOnlyHint: false`, `destructiveHint: false`, `idempotentHint: false`. It creates a billed task.
40
+ - `people-search-control`: `readOnlyHint: false`, `destructiveHint: true` (cancel cannot be undone), `idempotentHint: true`.
41
+
3
42
  ## 0.1.4
4
43
 
5
44
  `ai-search` tools enum drops `youtube`. Allowed ids are `web`, `twitter`, `arxiv`, `wikipedia`, `hackernews`, and `reddit`.
@@ -57,7 +96,7 @@ Node.js `>=20.18.1`. Node 22 is supported. Node 18 is not. `desearch-js` loads `
57
96
 
58
97
  ### Tool annotations
59
98
 
60
- `tools/list` sets MCP tool annotations on every tool:
99
+ In 0.1.2, `tools/list` set MCP tool annotations on every tool in that release:
61
100
 
62
101
  - `readOnlyHint: true` — the tool reads Desearch, the web, or X and does not write caller state
63
102
  - `destructiveHint: false` — it does not perform a destructive update
package/README.md CHANGED
@@ -1,15 +1,68 @@
1
1
  # Desearch MCP Server
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/desearch-mcp-server.svg)](https://www.npmjs.com/package/desearch-mcp-server)
4
+ [![GitHub stars](https://img.shields.io/github/stars/Desearch-ai/mcp-desearch?style=social)](https://github.com/Desearch-ai/mcp-desearch/stargazers)
4
5
 
5
- AI search, X search and web search for AI agents, plus page extraction and X data tools. Bring your own Desearch API key.
6
+ If Desearch is useful, a [star](https://github.com/Desearch-ai/mcp-desearch/stargazers) helps others find it.
7
+
8
+ Remote: `https://mcp.desearch.ai/mcp` with header `Authorization: Bearer <DESEARCH_API_KEY>`.
9
+
10
+ Local: `npx -y desearch-mcp-server` with env `DESEARCH_API_KEY`.
11
+
12
+ [Get a key](https://console.desearch.ai/api-keys).
13
+
14
+ ## Find Desearch on
15
+
16
+ - [Official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Desearch-ai/mcp-desearch)
17
+ - [Smithery](https://smithery.ai/servers/desearch/desearch)
18
+ - [Glama](https://glama.ai/mcp/servers/Desearch-ai/mcp-desearch)
19
+ - [VoltAgent official MCP servers](https://github.com/VoltAgent/official-mcp-servers#search-and-research)
20
+ - [Gemini CLI extensions](https://geminicli.com/extensions/)
21
+ - [Raycast MCP Registry](https://www.raycast.com/raycast/model-context-protocol-registry)
22
+
23
+ ## Demo
24
+
25
+ Prompt: Search the web for latest news on AI.
26
+
27
+ `web-search` takes `query` (required) and `start` (optional pagination offset: 0, 10, 20, ...).
28
+
29
+ ```json
30
+ {
31
+ "name": "web-search",
32
+ "arguments": {
33
+ "query": "latest news on AI"
34
+ }
35
+ }
36
+ ```
37
+
38
+ Example output:
39
+
40
+ ```json
41
+ {
42
+ "data": [
43
+ {
44
+ "title": "Example result",
45
+ "link": "https://example.com/page",
46
+ "snippet": "Short preview text."
47
+ }
48
+ ]
49
+ }
50
+ ```
51
+
52
+ The tool returns that JSON as pretty-printed text: `{ "content": [{ "type": "text", "text": "<json above>" }] }`.
53
+
54
+ AI search, X search and web search for AI agents, plus page extraction, X data tools, and People Search (find people and creators on X, YouTube, LinkedIn, and TikTok). Bring your own Desearch API key.
6
55
 
7
56
  ## Tools
8
57
 
9
- The Desearch MCP server includes the following tools:
58
+ The Desearch MCP server includes the following tools.
59
+
60
+ Lookup tools, including `search` and `fetch`, set `readOnlyHint: true`, `destructiveHint: false`, and `openWorldHint: true`. `people-search` starts a billed background job, so `readOnlyHint` is false and `destructiveHint` is false. `people-search-control` can cancel a search, so `readOnlyHint` is false and `destructiveHint` is true. `openWorldHint` is true on every tool because the call reaches a live external source.
10
61
 
11
62
  - **AI Search** (`ai-search`): Performs AI Twitter and web searches with relevant links and summary. `tools` uses short source ids (`web`, `twitter`, `arxiv`, `wikipedia`, `hackernews`, `reddit`). Older labels such as `Web Search`, `ArXiv Search`, `Wikipedia Search`, `Hacker News Search`, and `Reddit Search` are still accepted and sent as the short id. `youtube` is not accepted. Default is `["web", "twitter"]`.
12
63
  - **X Search** (`x-search`): Tweet search on X. Arguments: `query` (required), `count` (optional, default 20). Sort stays Top. Optional filters: `user`, `start_date`, `end_date` (YYYY-MM-DD), `lang`, `verified`, `blue_verified`, `is_quote`, `is_video`, `is_image`, `min_retweets`, `min_replies`, `min_likes`.
64
+ - **Search** (`search`): Web search that returns `{ results: [{ id, title, url }] }`. Argument: `query` (required). `id` is the result URL.
65
+ - **Fetch Page** (`fetch`): Read a public page as text. Argument: `id` (required, an `http` or `https` URL from `search`).
13
66
  - **Web Search** (`web-search`): SERP-style web search. Arguments: `query` (required), `start` (optional pagination offset).
14
67
  - **Web Links Search** (`web-links-search`): Web link search. Arguments: `prompt` (required), `tools` (optional, only `web`, default `["web"]`; `Web Search` is accepted and rewritten to `web`), `count` (optional, 10–200). The links/web API rejects other sources, so they are not in the enum.
15
68
  - **Extract** (`extract`): Read a public URL as text or HTML. Preferred over crawl. Arguments: `url` (required), `format` (optional, `html` or `text`), `js` (optional), `wait` (optional milliseconds).
@@ -23,8 +76,108 @@ The Desearch MCP server includes the following tools:
23
76
  - **X User Replies** (`x-user-replies`): Posts and replies by a user. Arguments: `user` (required), `count` (optional, 1–100), `query` (optional).
24
77
  - **X Post Replies** (`x-post-replies`): Replies to a post. Arguments: `post_id` (required), `count` (optional, 1–100), `query` (optional).
25
78
  - **X Trends** (`x-trends`): Trending topics for a location. Arguments: `woeid` (required), `count` (optional, 30–100).
79
+ - **People Search** (`people-search`): Start a search for people who match a plain-language description. **Billed.** Arguments: `platform` (required: `x`, `youtube`, `linkedin`, or `tiktok`), `query` (required, 3–1000 characters), `count` (optional, 5–200, API default 25), `min_score` (optional, 0–100), `exclude` (optional handles), `idempotency_key` (optional), and that platform's filters (below). Returns the `task_id`, status, and `reserved_cost_usd`.
80
+ - **People Search Status** (`people-search-status`): A task's status, progress, and cost, plus a page of the people found so far. Arguments: `task_id` (required), `cursor` (optional, `next_cursor` from the previous call), `limit` (optional, 1–100, default 25), `include_people` (optional, default `true`). Free.
81
+ - **Control People Search** (`people-search-control`): Pause, resume, or cancel a task. Arguments: `task_id` (required), `action` (required: `pause`, `resume`, or `cancel`). Free.
82
+ - **List People Search Tasks** (`people-search-tasks`): Your searches, newest first. Arguments: `platform` (optional), `status` (optional list, for example `["running", "paused"]`), `limit` (optional, 1–100), `cursor` (optional). Free.
83
+ - **List People Found** (`people-profiles`): Everyone your searches found on one platform, one entry per person, with the search that found them. Arguments: `platform` (required), `q` (optional text in name, handle, bio, or location), `sort` (optional: `score`, `recent`, or `audience`), `limit` (optional, 1–200, default 25), `cursor` (optional), and the filters `has` (channels every person must have: `email`, `website`, `x`, `linkedin`, `instagram`, `youtube`, `tiktok`), `min_audience`, `max_audience`, `min_score`, `location`, `verified`. Free.
84
+
85
+ The full SDK method → endpoint → MCP tool map is in [docs/API_MCP_PARITY.md](docs/API_MCP_PARITY.md). Every public `desearch-js` 1.5 method is a tool. `latestTweets` was removed from the SDK (`GET /twitter/latest` in 1.0.1) and is not exposed. People Search is not in `desearch-js` 1.5; its tools call the `/desearch/people/*` routes directly, and the parity doc lists them too.
86
+
87
+ ### People Search
88
+
89
+ People Search finds X profiles, YouTube creators, LinkedIn members, or TikTok creators who match a plain-language description. Each person comes back with a fit score, one line on why they matched, their audience (followers, or subscribers on YouTube), location, and the public contacts and links the search found.
90
+
91
+ A search is a background task:
92
+
93
+ 1. `people-search` starts it and returns a `task_id` at once. It is the only billed People Search call. It reserves `count` people at the platform's per-person price (`reserved_cost_usd`). When the search ends you pay only for the people it delivered (a per-search minimum applies when it finds anyone; a search that finds no one is free), and the rest of the reservation is returned. Send the same `idempotency_key` to retry a call without starting, or paying for, a second search.
94
+ 2. The search usually runs for 1 to 5 minutes. `people-search-status` returns its status, progress, cost, and the people found so far. People arrive while it runs: pass `next_cursor` back as `cursor` to get only the new ones. When `done` is `true` and `has_more` is `false`, you have everyone it found.
95
+ 3. `people-search-control` pauses, resumes, or cancels it. A cancelled search bills only the people it already delivered.
96
+
97
+ People found stay readable for 30 days after a search ends. `people-profiles` lists them per platform across all your searches, with filters such as `has: ["email"]`.
98
+
99
+ Search filters depend on the platform. A filter that does not apply is rejected before the billed call.
100
+
101
+ | Platform | Filters |
102
+ | --- | --- |
103
+ | `x` | `min_followers`, `max_followers`, `verified_only`, `countries`, `keywords`, `exclude_keywords` |
104
+ | `youtube` | `min_subscribers`, `max_subscribers`, `countries`, `require_contact`, `keywords`, `exclude_keywords` |
105
+ | `linkedin` | `min_followers`, `max_followers`, `countries`, `keywords`, `exclude_keywords` |
106
+ | `tiktok` | `min_followers`, `max_followers`, `require_contact`, `keywords`, `exclude_keywords` |
107
+
108
+ `require_contact` keeps only creators with a public email (on TikTok, in the bio). `keywords` and `exclude_keywords` take up to 20 words each.
26
109
 
27
- The full SDK method → endpoint → MCP tool map is in [docs/API_MCP_PARITY.md](docs/API_MCP_PARITY.md). Every public `desearch-js` 1.5 method is a tool. `latestTweets` was removed from the SDK (`GET /twitter/latest` in 1.0.1) and is not exposed.
110
+ Prompt: find 10 TikTok skincare creators with a public email.
111
+
112
+ ```json
113
+ {
114
+ "name": "people-search",
115
+ "arguments": {
116
+ "platform": "tiktok",
117
+ "query": "Skincare creators who review skincare products",
118
+ "count": 10,
119
+ "require_contact": true
120
+ }
121
+ }
122
+ ```
123
+
124
+ Example output:
125
+
126
+ ```json
127
+ {
128
+ "task_id": "3f1c2b9e-8d4a-4c1e-9b7a-2e5f6a7b8c9d",
129
+ "platform": "tiktok",
130
+ "status": "queued",
131
+ "done": false,
132
+ "query": "Skincare creators who review skincare products",
133
+ "count": 10,
134
+ "result_count": 0,
135
+ "reserved_cost_usd": 0.5,
136
+ "created_at": "2026-10-17T10:00:00Z",
137
+ "cost_usd": 0.5,
138
+ "currency": "USD",
139
+ "next": "Searches usually take 1 to 5 minutes. Poll people-search-status with this task_id every 15 to 30 seconds; people appear while it runs."
140
+ }
141
+ ```
142
+
143
+ Then poll with `{"task_id": "3f1c2b9e-8d4a-4c1e-9b7a-2e5f6a7b8c9d"}` on `people-search-status`:
144
+
145
+ ```json
146
+ {
147
+ "task_id": "3f1c2b9e-8d4a-4c1e-9b7a-2e5f6a7b8c9d",
148
+ "platform": "tiktok",
149
+ "status": "running",
150
+ "stage": "processing",
151
+ "done": false,
152
+ "query": "Skincare creators who review skincare products",
153
+ "count": 10,
154
+ "result_count": 4,
155
+ "progress": { "round": 1, "candidates_processed": 40, "qualified": 4 },
156
+ "reserved_cost_usd": 0.5,
157
+ "created_at": "2026-10-17T10:00:00Z",
158
+ "people": [
159
+ {
160
+ "id": "tiktok:example_creator",
161
+ "platform": "tiktok",
162
+ "handle": "example_creator",
163
+ "name": "Example Creator",
164
+ "url": "https://www.tiktok.com/@example_creator",
165
+ "audience": 48200,
166
+ "location": "United States",
167
+ "score": 88,
168
+ "why": "Reviews sunscreens and moisturizers every week.",
169
+ "contacts": [{ "type": "email", "value": "creator@example.com" }],
170
+ "links": [{ "type": "instagram", "url": "https://instagram.com/example_creator" }],
171
+ "evidence_url": "https://www.tiktok.com/@example_creator/video/1"
172
+ }
173
+ ],
174
+ "next_cursor": "4",
175
+ "has_more": false,
176
+ "next": "Still searching. Wait 15 to 30 seconds, then call people-search-status again with cursor \"4\" to get only the people found since this call."
177
+ }
178
+ ```
179
+
180
+ The output above is shortened to one person. CSV and JSON Lines downloads (`/export` routes) are not MCP tools; call the API directly for a file.
28
181
 
29
182
  ## Prerequisites 📋
30
183
 
@@ -254,8 +407,9 @@ Remote requests do not use that environment variable. Discovery does not need a
254
407
 
255
408
  - `Authorization: Bearer <DESEARCH_API_KEY>` (preferred)
256
409
  - `x-api-key: <DESEARCH_API_KEY>`
410
+ - `Authorization: Bearer <oauth access token>` after the OAuth sign-in below
257
411
 
258
- A bare `Authorization: <DESEARCH_API_KEY>` value is also accepted. The key is not read from the query string. There is no shared server secret and no `WWW-Authenticate` challenge: the hosted process forwards the per-request key to the Desearch API only when a call needs it.
412
+ A bare `Authorization: <DESEARCH_API_KEY>` value is also accepted. The key is not read from the query string. There is no shared server secret. A protected call without a valid key or access token returns 401 with a `WWW-Authenticate` header pointing at `/.well-known/oauth-protected-resource/mcp`. The hosted process forwards the per-request Desearch API key to the Desearch API only when a call needs it. An OAuth access token is opaque: the server looks up the key stored for that token and does not put the raw key in the token.
259
413
 
260
414
  The MCP endpoint is `POST /mcp`. Responses are JSON (stateless Streamable HTTP). `GET` and `DELETE` on `/mcp` return `405` because the server does not keep a session or push server-to-client messages. `GET /`, `GET /health`, and `GET /api/health` are unauthenticated health checks.
261
415
 
@@ -278,9 +432,54 @@ Cursor, or any remote MCP client:
278
432
  }
279
433
  ```
280
434
 
435
+ ### OAuth sign-in
436
+
437
+ Clients that follow the MCP authorization spec (2025-06-18) can sign in instead of sending a key on every request. Discovery documents:
438
+
439
+ - `GET /.well-known/oauth-protected-resource`
440
+ - `GET /.well-known/oauth-protected-resource/mcp`
441
+ - `GET /.well-known/oauth-authorization-server`
442
+ - `GET /.well-known/openid-configuration` (same authorization server document)
443
+
444
+ `POST /register` is dynamic client registration. `GET /authorize` is the Desearch page where the user pastes an API key. `POST /token` exchanges the authorization code and rotates refresh tokens. PKCE S256 is required. Public clients use `token_endpoint_auth_method` `none`.
445
+
446
+ Allowed callback URLs:
447
+
448
+ - `https://claude.ai/api/mcp/auth_callback`
449
+ - `https://claude.com/api/mcp/auth_callback`
450
+ - `https://chatgpt.com/connector_platform_oauth_redirect`
451
+ - `https://chatgpt.com/connector/oauth/{callback_id}`
452
+ - Loopback `http://localhost`, `http://127.0.0.1`, and `http://[::1]` on any port (host and path must match the registered callback)
453
+
454
+ The connector URL is `https://mcp.desearch.ai/mcp`. On the sign-in page, paste a key from [console.desearch.ai/api-keys](https://console.desearch.ai/api-keys). Leave a client id blank when the client can register itself.
455
+
456
+ Environment variables for the host:
457
+
458
+ | Variable | Required | Purpose |
459
+ | --- | --- | --- |
460
+ | `OAUTH_ISSUER` | Production | Canonical origin with no trailing slash, for example `https://mcp.desearch.ai`. Required when `NODE_ENV=production` or `VERCEL` is set. The process refuses OAuth and bearer challenges if it is unset. The issuer is never taken from `X-Forwarded-Host`. Locally, the request URL is used. |
461
+ | `OAUTH_RESOURCE` | No | Canonical MCP URL. Default is `{OAUTH_ISSUER}/mcp`. Access tokens are rejected when their stored audience does not match this resource. |
462
+ | `OAUTH_STORE` | Production | `memory` (local default) or `redis`. Production (`NODE_ENV=production` or `VERCEL`) refuses to start unless this is `redis`. |
463
+ | `REDIS_URL` | When `OAUTH_STORE=redis` | Redis connection string (`redis://` or `rediss://`). |
464
+ | `OAUTH_ENCRYPTION_KEY` | When `OAUTH_STORE=redis` | 32-byte key, base64 or hex. Generate with `openssl rand -base64 32`. Encrypts stored API keys. |
465
+ | `OAUTH_ACCESS_TTL_SEC` | No | Access token lifetime. Default 3600. Range 60 to 86400. |
466
+ | `OAUTH_REFRESH_TTL_SEC` | No | Refresh token lifetime. Default 30 days. Range 300 to 90 days. |
467
+ | `OAUTH_CODE_TTL_SEC` | No | Authorization code lifetime. Default 300. Range 30 to 600. |
468
+ | `OAUTH_CLIENT_TTL_SEC` | No | Dynamic client lifetime. Default 90 days. Range 3600 to 5 years. |
469
+ | `OAUTH_REGISTER_RATE_LIMIT` | No | Registration attempts per IP per window. Default 10. Range 1 to 10000. |
470
+ | `OAUTH_REGISTER_RATE_WINDOW_SEC` | No | Registration rate-limit window in seconds. Default 3600 (1 hour). Range 1 to 86400. |
471
+ | `OAUTH_AUTHORIZE_RATE_LIMIT` | No | Sign-in key checks per IP per window. Default 20. Range 1 to 10000. |
472
+ | `OAUTH_AUTHORIZE_RATE_WINDOW_SEC` | No | Sign-in key-check window in seconds. Default 600 (10 minutes). Range 1 to 86400. |
473
+ | `DESEARCH_API_BASE` | No | Key check host. Default `https://api.desearch.ai`. |
474
+ | `OAUTH_REQUIRE_AUTH_ON_INITIALIZE` | No | Set to `true` to require a key or access token on `initialize`. Default is off, so keyless `initialize` stays public. `tools/list` stays public either way. |
475
+
476
+ The key check calls `GET /twitter/trends?woeid=1&count=1`. A real key is authenticated and then rejected as invalid input (HTTP 422), so the check does not run a full trends query. Only 422 counts as a valid key. `401` and `403` reject the key. Any other status, including a 2xx, is a verification error and is not treated as valid.
477
+
478
+ `POST /register` allows 10 requests an hour per IP. The sign-in key check allows 20 requests every 10 minutes per IP. A request past the limit returns 429 with `Retry-After`. On Vercel the address is the first `X-Forwarded-For` hop. The sign-in form accepts a same-origin `Origin` or `Referer`, and rejects a POST that sends none of `Origin`, `Referer`, and `Sec-Fetch-Site`.
479
+
281
480
  ### Use with Claude (custom connector)
282
481
 
283
- Desearch is not in the Claude Connectors Directory yet. You can add the hosted server as a custom connector with your Desearch API key.
482
+ Desearch is not in the Claude Connectors Directory yet. You can add the hosted server as a custom connector with your Desearch API key, or with OAuth sign-in.
284
483
 
285
484
  Sources: [Custom remote MCP connectors](https://claude.com/docs/connectors/custom/remote-mcp) and [connector authentication](https://claude.com/docs/connectors/building/authentication). Request-header authentication is a beta feature in Claude.
286
485
 
@@ -295,6 +494,8 @@ Sources: [Custom remote MCP connectors](https://claude.com/docs/connectors/custo
295
494
 
296
495
  The header value is stored once and shared by everyone in the organization who uses the connector.
297
496
 
497
+ OAuth alternative: choose sign-in instead of a request header, leave the OAuth client id empty so the client can register itself, and paste a Desearch API key on the Desearch page. The callback URL for hosted Claude apps is `https://claude.ai/api/mcp/auth_callback`. Claude Code uses a loopback callback, which this server accepts on any port.
498
+
298
499
  **Claude Code**
299
500
 
300
501
  ```bash
@@ -351,7 +552,9 @@ docker run --rm -e MCP_TRANSPORT=http -p 3000:3000 desearch-mcp
351
552
 
352
553
  ### Deploy on Vercel
353
554
 
354
- Vercel fits this server because the handler is stateless and answers each JSON-RPC call in one response. `vercel.json` builds the project, serves `POST /mcp`, and sets the function duration to 60 seconds. Hobby plans cap function duration lower than that, so AI Search tool calls need a plan that allows at least 60 seconds. `initialize` and `tools/list` are short either way.
555
+ Vercel fits the MCP handler because each JSON-RPC call is one response. `vercel.json` builds the project, serves `POST /mcp`, and sets the function duration to 60 seconds. Hobby plans cap function duration lower than that, so AI Search tool calls need a plan that allows at least 60 seconds. `initialize` and `tools/list` are short either way.
556
+
557
+ OAuth codes and tokens need shared storage. On Vercel set `OAUTH_STORE=redis`, `REDIS_URL`, `OAUTH_ENCRYPTION_KEY`, and `OAUTH_ISSUER=https://mcp.desearch.ai`. The server refuses OAuth when `OAUTH_ISSUER` is unset or `OAUTH_STORE` is not `redis`, because Vercel sets `VERCEL` on every function. `OAUTH_REQUIRE_AUTH_ON_INITIALIZE=true` is optional. Leave it unset unless a client treats public `initialize` as a reason to skip sign-in.
355
558
 
356
559
  No server-side Desearch API key is required in the Vercel project. After deploy, the endpoint is:
357
560
 
package/build/http.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { extractDesearchApiKey } from "./request-key.js";
2
+ export { extractDesearchApiKey };
1
3
  export interface HttpListenOptions {
2
4
  port?: number;
3
5
  host?: string;
@@ -7,19 +9,11 @@ export interface RunningHttpServer {
7
9
  host: string;
8
10
  close: () => Promise<void>;
9
11
  }
10
- /**
11
- * Desearch API key from the remote client.
12
- * Prefer `Authorization: Bearer <key>` (what MCP clients send). `x-api-key` is
13
- * accepted as well. A bare `Authorization: <key>` value is accepted so the same
14
- * string used as `DESEARCH_API_KEY` for stdio can be sent without a scheme.
15
- * Query strings are ignored so keys do not land in access logs.
16
- */
17
12
  /**
18
13
  * Copy a request onto another path. Used by the Vercel functions, which see
19
14
  * the rewritten URL (`/api/mcp`) rather than the public path (`/mcp`).
20
15
  */
21
16
  export declare function requestWithPathname(request: Request, pathname: string): Request;
22
- export declare function extractDesearchApiKey(request: Request): string | undefined;
23
17
  /**
24
18
  * Stateless Streamable HTTP handler.
25
19
  * Each POST builds a fresh MCP server tied to that request's API key.
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../http.ts"],"names":[],"mappings":"AAsBA,MAAM,WAAW,iBAAiB;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAED;;;;;;GAMG;AACH;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAa/E;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAkB1E;AAkID;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiE9E;AAuDD,wBAAgB,eAAe,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAiD3F"}
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../http.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAGzD,OAAO,EAAE,qBAAqB,EAAE,CAAC;AAoBjC,MAAM,WAAW,iBAAiB;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAa/E;AAiOD;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgF9E;AA2DD,wBAAgB,eAAe,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAiD3F"}
package/build/http.js CHANGED
@@ -1,11 +1,17 @@
1
1
  import { createServer } from "node:http";
2
2
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
3
+ import { DIRECT_CLIENT_IP_HEADER } from "./oauth/client-ip.js";
4
+ import { OAuthConfigError } from "./oauth/errors.js";
5
+ import { handleOAuthHttp, resolveRequestCredential } from "./oauth/http.js";
6
+ import { wwwAuthenticate } from "./oauth/metadata.js";
7
+ import { extractDesearchApiKey } from "./request-key.js";
3
8
  import { createDesearchMcpServer, SERVER_NAME, SERVER_VERSION } from "./server.js";
9
+ export { extractDesearchApiKey };
4
10
  const CORS_HEADERS = {
5
11
  "Access-Control-Allow-Origin": "*",
6
12
  "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
7
13
  "Access-Control-Allow-Headers": "Content-Type, Accept, Authorization, x-api-key, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID",
8
- "Access-Control-Expose-Headers": "Mcp-Session-Id",
14
+ "Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate",
9
15
  "Access-Control-Max-Age": "86400",
10
16
  };
11
17
  const HOP_BY_HOP = new Set([
@@ -16,13 +22,6 @@ const HOP_BY_HOP = new Set([
16
22
  "host",
17
23
  "content-length",
18
24
  ]);
19
- /**
20
- * Desearch API key from the remote client.
21
- * Prefer `Authorization: Bearer <key>` (what MCP clients send). `x-api-key` is
22
- * accepted as well. A bare `Authorization: <key>` value is accepted so the same
23
- * string used as `DESEARCH_API_KEY` for stdio can be sent without a scheme.
24
- * Query strings are ignored so keys do not land in access logs.
25
- */
26
25
  /**
27
26
  * Copy a request onto another path. Used by the Vercel functions, which see
28
27
  * the rewritten URL (`/api/mcp`) rather than the public path (`/mcp`).
@@ -41,23 +40,6 @@ export function requestWithPathname(request, pathname) {
41
40
  }
42
41
  return new Request(url, init);
43
42
  }
44
- export function extractDesearchApiKey(request) {
45
- const authorization = request.headers.get("authorization")?.trim();
46
- if (authorization) {
47
- const bearer = /^Bearer\s+(\S+)$/i.exec(authorization);
48
- if (bearer?.[1]) {
49
- return bearer[1];
50
- }
51
- if (!/^Bearer\b/i.test(authorization) && !/\s/.test(authorization)) {
52
- return authorization;
53
- }
54
- }
55
- const headerKey = request.headers.get("x-api-key")?.trim();
56
- if (headerKey) {
57
- return headerKey;
58
- }
59
- return undefined;
60
- }
61
43
  function normalizePath(pathname) {
62
44
  if (pathname.length > 1 && pathname.endsWith("/")) {
63
45
  return pathname.slice(0, -1);
@@ -99,16 +81,95 @@ function healthResponse() {
99
81
  version: SERVER_VERSION,
100
82
  transport: "streamable-http",
101
83
  endpoint: "/mcp",
102
- auth: "initialize and tools/list are public. tools/call requires Authorization: Bearer <DESEARCH_API_KEY> or x-api-key.",
84
+ auth: "initialize and tools/list are public. tools/call requires Authorization: Bearer <DESEARCH_API_KEY>, x-api-key, or an OAuth access token.",
103
85
  }), {
104
86
  status: 200,
105
87
  headers: { "Content-Type": "application/json" },
106
88
  });
107
89
  }
108
- function unauthorized() {
109
- // No OAuth challenge. Desearch auth is a per-user API key, and a
110
- // WWW-Authenticate discovery hint makes some MCP clients start an OAuth flow.
111
- return jsonRpcError(401, -32001, "Unauthorized. Send your Desearch API key in the Authorization: Bearer <key> header or the x-api-key header.");
90
+ const INVALID_TOKEN_CHALLENGE = {
91
+ error: "invalid_token",
92
+ error_description: "The access token is invalid or expired.",
93
+ };
94
+ const LOGIN_CHALLENGE = {
95
+ error: "insufficient_scope",
96
+ error_description: "You need to login to continue",
97
+ };
98
+ const UNAUTHORIZED_MESSAGE = "Unauthorized. Send your Desearch API key in the Authorization: Bearer <key> header or the x-api-key header.";
99
+ function challengeHeader(request, challenge) {
100
+ try {
101
+ return wwwAuthenticate(request, challenge);
102
+ }
103
+ catch (error) {
104
+ if (error instanceof OAuthConfigError) {
105
+ return jsonRpcError(500, -32603, "Authorization storage is unavailable.");
106
+ }
107
+ throw error;
108
+ }
109
+ }
110
+ function unauthorized(request, invalidToken = false) {
111
+ const header = challengeHeader(request, invalidToken ? INVALID_TOKEN_CHALLENGE : undefined);
112
+ if (header instanceof Response) {
113
+ return header;
114
+ }
115
+ return jsonRpcError(401, -32001, UNAUTHORIZED_MESSAGE, { "WWW-Authenticate": header });
116
+ }
117
+ function readToolsCalls(raw) {
118
+ let parsed;
119
+ try {
120
+ parsed = JSON.parse(raw);
121
+ }
122
+ catch {
123
+ return null;
124
+ }
125
+ const batched = Array.isArray(parsed);
126
+ const messages = batched ? parsed : [parsed];
127
+ if (messages.length === 0) {
128
+ return null;
129
+ }
130
+ const calls = [];
131
+ for (const message of messages) {
132
+ if (typeof message !== "object" || message === null) {
133
+ return null;
134
+ }
135
+ if (message.method !== "tools/call") {
136
+ return null;
137
+ }
138
+ calls.push(message);
139
+ }
140
+ return { batched, calls };
141
+ }
142
+ function authFailure(request, raw, invalidToken) {
143
+ const header = challengeHeader(request, invalidToken ? INVALID_TOKEN_CHALLENGE : undefined);
144
+ if (header instanceof Response) {
145
+ return header;
146
+ }
147
+ const metaHeader = invalidToken ? header : challengeHeader(request, LOGIN_CHALLENGE);
148
+ if (metaHeader instanceof Response) {
149
+ return metaHeader;
150
+ }
151
+ const tools = readToolsCalls(raw);
152
+ if (!tools) {
153
+ return jsonRpcError(401, -32001, UNAUTHORIZED_MESSAGE, { "WWW-Authenticate": header });
154
+ }
155
+ const results = tools.calls.map((call) => ({
156
+ jsonrpc: "2.0",
157
+ id: call.id ?? null,
158
+ result: {
159
+ content: [{ type: "text", text: UNAUTHORIZED_MESSAGE }],
160
+ isError: true,
161
+ _meta: {
162
+ "mcp/www_authenticate": [`'${metaHeader}'`],
163
+ },
164
+ },
165
+ }));
166
+ return new Response(JSON.stringify(tools.batched ? results : results[0]), {
167
+ status: 401,
168
+ headers: {
169
+ "Content-Type": "application/json",
170
+ "WWW-Authenticate": header,
171
+ },
172
+ });
112
173
  }
113
174
  /**
114
175
  * Methods a marketplace scanner can call with no Desearch API key.
@@ -124,6 +185,15 @@ const KEYLESS_METHODS = new Set([
124
185
  "resources/list",
125
186
  "resources/templates/list",
126
187
  ]);
188
+ function authRequiredOnInitialize() {
189
+ return /^(1|true|yes)$/i.test((process.env.OAUTH_REQUIRE_AUTH_ON_INITIALIZE ?? "").trim());
190
+ }
191
+ function isKeylessMethod(method) {
192
+ if (method === "initialize" && authRequiredOnInitialize()) {
193
+ return false;
194
+ }
195
+ return KEYLESS_METHODS.has(method);
196
+ }
127
197
  function isKeylessDiscovery(raw) {
128
198
  let parsed;
129
199
  try {
@@ -139,7 +209,7 @@ function isKeylessDiscovery(raw) {
139
209
  return false;
140
210
  }
141
211
  const method = message.method;
142
- return typeof method === "string" && KEYLESS_METHODS.has(method);
212
+ return typeof method === "string" && isKeylessMethod(method);
143
213
  }));
144
214
  }
145
215
  function copyRequestHeaders(headers) {
@@ -178,6 +248,10 @@ export async function handleMcpHttpRequest(request) {
178
248
  return withCors(new Response(null, { status: 204 }));
179
249
  }
180
250
  const pathname = normalizePath(new URL(request.url).pathname);
251
+ const oauthResponse = await handleOAuthHttp(request);
252
+ if (oauthResponse) {
253
+ return withCors(oauthResponse);
254
+ }
181
255
  if (isHealthPath(pathname)) {
182
256
  if (request.method === "GET") {
183
257
  return withCors(healthResponse());
@@ -190,20 +264,31 @@ export async function handleMcpHttpRequest(request) {
190
264
  headers: { "Content-Type": "application/json" },
191
265
  }));
192
266
  }
267
+ const credential = await resolveRequestCredential(request);
268
+ if (credential.kind === "unavailable") {
269
+ return withCors(jsonRpcError(500, -32603, "Authorization storage is unavailable."));
270
+ }
193
271
  if (request.method === "GET" || request.method === "DELETE") {
194
- if (!extractDesearchApiKey(request)) {
195
- return withCors(unauthorized());
272
+ if (credential.kind !== "key") {
273
+ return withCors(unauthorized(request, credential.kind === "unauthorized"));
196
274
  }
197
275
  return withCors(jsonRpcError(405, -32000, "Method not allowed. This server is stateless; use POST.", { Allow: "POST" }));
198
276
  }
199
277
  if (request.method !== "POST") {
200
278
  return withCors(jsonRpcError(405, -32000, "Method not allowed.", { Allow: "POST" }));
201
279
  }
202
- let apiKey = extractDesearchApiKey(request);
203
- if (!apiKey) {
280
+ let apiKey;
281
+ if (credential.kind === "key") {
282
+ apiKey = credential.apiKey;
283
+ }
284
+ else if (credential.kind === "unauthorized") {
285
+ const raw = await request.text();
286
+ return withCors(authFailure(request, raw, true));
287
+ }
288
+ else {
204
289
  const raw = await request.text();
205
290
  if (!isKeylessDiscovery(raw)) {
206
- return withCors(unauthorized());
291
+ return withCors(authFailure(request, raw, false));
207
292
  }
208
293
  request = requestWithJsonBody(request, raw);
209
294
  apiKey = "";
@@ -247,7 +332,7 @@ async function toWebRequest(req) {
247
332
  const url = `http://${host}${req.url ?? "/"}`;
248
333
  const headers = new Headers();
249
334
  for (const [key, value] of Object.entries(req.headers)) {
250
- if (value === undefined || HOP_BY_HOP.has(key.toLowerCase())) {
335
+ if (value === undefined || HOP_BY_HOP.has(key.toLowerCase()) || key.toLowerCase() === DIRECT_CLIENT_IP_HEADER) {
251
336
  continue;
252
337
  }
253
338
  if (Array.isArray(value)) {
@@ -259,6 +344,10 @@ async function toWebRequest(req) {
259
344
  headers.set(key, value);
260
345
  }
261
346
  }
347
+ const remote = req.socket?.remoteAddress;
348
+ if (remote) {
349
+ headers.set(DIRECT_CLIENT_IP_HEADER, remote);
350
+ }
262
351
  const method = req.method ?? "GET";
263
352
  const hasBody = method !== "GET" && method !== "HEAD";
264
353
  const body = hasBody ? await readRawBody(req) : undefined;
@@ -0,0 +1,10 @@
1
+ /** Stamped by the Node HTTP server from the socket. Ignored when `VERCEL` is set. */
2
+ export declare const DIRECT_CLIENT_IP_HEADER = "x-desearch-remote-address";
3
+ /**
4
+ * Address used for per-IP limits.
5
+ * On Vercel the platform puts the client first in `X-Forwarded-For` and appends
6
+ * proxies, so the first hop is the caller. Off Vercel that header is chosen by
7
+ * the client and is ignored. The Node server stamps the socket address instead.
8
+ */
9
+ export declare function clientIp(request: Request): string;
10
+ //# sourceMappingURL=client-ip.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-ip.d.ts","sourceRoot":"","sources":["../../oauth/client-ip.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,eAAO,MAAM,uBAAuB,8BAA8B,CAAC;AAEnE;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CASjD"}
@@ -0,0 +1,28 @@
1
+ /** Stamped by the Node HTTP server from the socket. Ignored when `VERCEL` is set. */
2
+ export const DIRECT_CLIENT_IP_HEADER = "x-desearch-remote-address";
3
+ /**
4
+ * Address used for per-IP limits.
5
+ * On Vercel the platform puts the client first in `X-Forwarded-For` and appends
6
+ * proxies, so the first hop is the caller. Off Vercel that header is chosen by
7
+ * the client and is ignored. The Node server stamps the socket address instead.
8
+ */
9
+ export function clientIp(request) {
10
+ if (process.env.VERCEL) {
11
+ return firstForwardedHop(request.headers.get("x-forwarded-for")) ?? "unknown";
12
+ }
13
+ const direct = request.headers.get(DIRECT_CLIENT_IP_HEADER)?.trim();
14
+ if (direct) {
15
+ return direct.slice(0, 128);
16
+ }
17
+ return "unknown";
18
+ }
19
+ function firstForwardedHop(value) {
20
+ if (!value) {
21
+ return null;
22
+ }
23
+ const first = value.split(",")[0]?.trim().replace(/^"|"$/g, "");
24
+ if (!first) {
25
+ return null;
26
+ }
27
+ return first.slice(0, 128);
28
+ }