x-search-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Konark Mangudkar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # x-search-mcp
2
+
3
+ Minimal MCP server for xAI X search using the Responses API and structured outputs.
4
+
5
+ ## Features
6
+ - Single MCP tool: `x_search`
7
+ - Uses xAI Responses API with `x_search` tool calling
8
+ - Structured output parsing + citation normalization
9
+
10
+ ## Requirements
11
+ - Node.js >= 18
12
+ - `XAI_API_KEY` environment variable
13
+
14
+ ## Install
15
+ ```bash
16
+ npm install
17
+ npm run build
18
+ ```
19
+
20
+ ## Run (stdio)
21
+ ```bash
22
+ XAI_API_KEY=your-key-here node dist/index.js
23
+ ```
24
+
25
+ ## Codex MCP config (example)
26
+ ```toml
27
+ [mcp_servers.x-search]
28
+ command = "node"
29
+ args = ["/path/to/x-search-mcp/dist/index.js"]
30
+ [mcp_servers.x-search.env]
31
+ XAI_API_KEY = "your-key-here"
32
+ ```
33
+
34
+ ## Smoke test (optional)
35
+ ```bash
36
+ XAI_API_KEY=your-key-here npm run build
37
+ XAI_API_KEY=your-key-here npm run smoke-test
38
+ ```
39
+ Note: this test requires network access and may fail in restricted environments.
40
+
41
+ ## MCP Tool
42
+ ### `x_search`
43
+ Searches X with optional filters.
44
+
45
+ **Input**
46
+ ```json
47
+ {
48
+ "query": "string",
49
+ "allowed_x_handles": ["string"],
50
+ "excluded_x_handles": ["string"],
51
+ "from_date": "YYYY-MM-DD",
52
+ "to_date": "YYYY-MM-DD",
53
+ "enable_image_understanding": true,
54
+ "enable_video_understanding": true,
55
+ "include_raw_response": false
56
+ }
57
+ ```
58
+
59
+ **Output**
60
+ ```json
61
+ {
62
+ "answer": "string",
63
+ "citations": ["https://x.com/..."],
64
+ "inline_citations": [
65
+ {
66
+ "url": "https://x.com/...",
67
+ "start_index": 10,
68
+ "end_index": 42,
69
+ "title": "1"
70
+ }
71
+ ],
72
+ "raw_response": {}
73
+ }
74
+ ```
75
+
76
+ ## Environment Variables
77
+ - `XAI_API_KEY` (required)
78
+ - `XAI_MODEL` (default: `grok-4-1-fast`)
79
+ - `XAI_BASE_URL` (default: `https://api.x.ai/v1`)
80
+ - `XAI_TIMEOUT` (default: `30000`)
81
+
82
+ ## Notes
83
+ - `allowed_x_handles` and `excluded_x_handles` are mutually exclusive.
84
+ - Date filters must be `YYYY-MM-DD` and `from_date` must be <= `to_date`.
85
+ - Tool responses are returned as MCP `structuredContent` (with a text fallback for display).
86
+ - Citations are normalized from xAI response annotations when available.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/index.js";
package/dist/index.js ADDED
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+ const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
6
+ const DEFAULT_MODEL = "grok-4-1-fast";
7
+ const XSearchInputBaseSchema = z.object({
8
+ query: z.string().min(1).max(2000).describe("Search query for X"),
9
+ allowed_x_handles: z
10
+ .array(z.string().min(1))
11
+ .max(10)
12
+ .optional()
13
+ .describe("Only include posts from these handles"),
14
+ excluded_x_handles: z
15
+ .array(z.string().min(1))
16
+ .max(10)
17
+ .optional()
18
+ .describe("Exclude posts from these handles"),
19
+ from_date: z
20
+ .string()
21
+ .optional()
22
+ .describe("Start date (YYYY-MM-DD)"),
23
+ to_date: z.string().optional().describe("End date (YYYY-MM-DD)"),
24
+ enable_image_understanding: z
25
+ .boolean()
26
+ .optional()
27
+ .describe("Enable image understanding"),
28
+ enable_video_understanding: z
29
+ .boolean()
30
+ .optional()
31
+ .describe("Enable video understanding"),
32
+ include_raw_response: z
33
+ .boolean()
34
+ .optional()
35
+ .describe("Include raw xAI response for debugging"),
36
+ });
37
+ const XSearchInputSchema = XSearchInputBaseSchema.superRefine((data, ctx) => {
38
+ if (data.allowed_x_handles && data.excluded_x_handles) {
39
+ ctx.addIssue({
40
+ code: z.ZodIssueCode.custom,
41
+ message: "allowed_x_handles and excluded_x_handles cannot both be set",
42
+ path: ["allowed_x_handles"],
43
+ });
44
+ }
45
+ if (data.from_date) {
46
+ const error = validateDateString(data.from_date);
47
+ if (error) {
48
+ ctx.addIssue({
49
+ code: z.ZodIssueCode.custom,
50
+ message: error,
51
+ path: ["from_date"],
52
+ });
53
+ }
54
+ }
55
+ if (data.to_date) {
56
+ const error = validateDateString(data.to_date);
57
+ if (error) {
58
+ ctx.addIssue({
59
+ code: z.ZodIssueCode.custom,
60
+ message: error,
61
+ path: ["to_date"],
62
+ });
63
+ }
64
+ }
65
+ if (data.from_date && data.to_date) {
66
+ const from = new Date(data.from_date);
67
+ const to = new Date(data.to_date);
68
+ if (from > to) {
69
+ ctx.addIssue({
70
+ code: z.ZodIssueCode.custom,
71
+ message: "from_date must be before or equal to to_date",
72
+ path: ["from_date"],
73
+ });
74
+ }
75
+ }
76
+ });
77
+ const XSearchOutputSchema = z.object({
78
+ answer: z.string(),
79
+ citations: z.array(z.string()),
80
+ inline_citations: z.array(z.object({
81
+ url: z.string(),
82
+ start_index: z.number().nullable(),
83
+ end_index: z.number().nullable(),
84
+ title: z.string().nullable(),
85
+ })),
86
+ raw_response: z.unknown().optional(),
87
+ });
88
+ const RESPONSE_SCHEMA = {
89
+ name: "x_search_answer",
90
+ schema: {
91
+ type: "object",
92
+ properties: {
93
+ answer: { type: "string" },
94
+ citations: { type: "array", items: { type: "string" } },
95
+ },
96
+ required: ["answer"],
97
+ },
98
+ };
99
+ function validateDateString(value) {
100
+ if (!DATE_REGEX.test(value)) {
101
+ return "Date must be in YYYY-MM-DD format";
102
+ }
103
+ const date = new Date(value);
104
+ if (Number.isNaN(date.getTime())) {
105
+ return "Invalid date";
106
+ }
107
+ const iso = date.toISOString().slice(0, 10);
108
+ if (iso !== value) {
109
+ return "Invalid date";
110
+ }
111
+ return null;
112
+ }
113
+ function dedupeUrls(urls) {
114
+ const seen = new Set();
115
+ const result = [];
116
+ for (const url of urls) {
117
+ if (!url)
118
+ continue;
119
+ if (seen.has(url))
120
+ continue;
121
+ seen.add(url);
122
+ result.push(url);
123
+ }
124
+ return result;
125
+ }
126
+ function extractMessage(output) {
127
+ if (!output)
128
+ return null;
129
+ const message = output.find((item) => item?.type === "message");
130
+ if (!message)
131
+ return null;
132
+ const content = message.content?.find((item) => item?.type === "output_text");
133
+ if (!content)
134
+ return null;
135
+ return content;
136
+ }
137
+ function normalizeCitations(annotations, parsedCitations) {
138
+ const urlCitations = (annotations || [])
139
+ .filter((a) => a?.type === "url_citation" && a?.url)
140
+ .map((a) => ({
141
+ url: a.url,
142
+ start_index: typeof a.start_index === "number" ? a.start_index : null,
143
+ end_index: typeof a.end_index === "number" ? a.end_index : null,
144
+ title: a.title ?? null,
145
+ }));
146
+ const urlsFromAnnotations = dedupeUrls(urlCitations.map((c) => c.url));
147
+ const urlsFromParsed = Array.isArray(parsedCitations)
148
+ ? parsedCitations.filter((c) => typeof c === "string" && c.startsWith("http"))
149
+ : [];
150
+ const citations = urlsFromAnnotations.length > 0 ? urlsFromAnnotations : urlsFromParsed;
151
+ return {
152
+ citations,
153
+ inline_citations: urlCitations,
154
+ };
155
+ }
156
+ async function fetchJson(url, options, timeoutMs) {
157
+ const controller = new AbortController();
158
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
159
+ try {
160
+ const response = await fetch(url, { ...options, signal: controller.signal });
161
+ const text = await response.text();
162
+ if (!response.ok) {
163
+ throw new Error(`xAI API error ${response.status}: ${text}`);
164
+ }
165
+ return JSON.parse(text);
166
+ }
167
+ finally {
168
+ clearTimeout(timeoutId);
169
+ }
170
+ }
171
+ const server = new McpServer({
172
+ name: "x-search-mcp",
173
+ version: "0.1.0",
174
+ });
175
+ server.registerTool("x_search", {
176
+ title: "X Search",
177
+ description: "Search X posts using xAI's Responses API x_search tool. Returns a normalized answer and citations.",
178
+ inputSchema: XSearchInputBaseSchema,
179
+ outputSchema: XSearchOutputSchema,
180
+ annotations: {
181
+ readOnlyHint: true,
182
+ idempotentHint: false,
183
+ openWorldHint: true,
184
+ },
185
+ }, async (args) => {
186
+ try {
187
+ const parsedArgs = XSearchInputSchema.parse(args);
188
+ const apiKey = process.env.XAI_API_KEY;
189
+ if (!apiKey) {
190
+ throw new Error("XAI_API_KEY is required");
191
+ }
192
+ const baseUrl = process.env.XAI_BASE_URL ?? "https://api.x.ai/v1";
193
+ const model = process.env.XAI_MODEL ?? DEFAULT_MODEL;
194
+ const timeoutMs = Number.parseInt(process.env.XAI_TIMEOUT ?? "30000", 10);
195
+ const toolConfig = {
196
+ type: "x_search",
197
+ };
198
+ if (parsedArgs.allowed_x_handles) {
199
+ toolConfig.allowed_x_handles = parsedArgs.allowed_x_handles;
200
+ }
201
+ if (parsedArgs.excluded_x_handles) {
202
+ toolConfig.excluded_x_handles = parsedArgs.excluded_x_handles;
203
+ }
204
+ if (parsedArgs.from_date) {
205
+ toolConfig.from_date = parsedArgs.from_date;
206
+ }
207
+ if (parsedArgs.to_date) {
208
+ toolConfig.to_date = parsedArgs.to_date;
209
+ }
210
+ if (typeof parsedArgs.enable_image_understanding === "boolean") {
211
+ toolConfig.enable_image_understanding = parsedArgs.enable_image_understanding;
212
+ }
213
+ if (typeof parsedArgs.enable_video_understanding === "boolean") {
214
+ toolConfig.enable_video_understanding = parsedArgs.enable_video_understanding;
215
+ }
216
+ const body = {
217
+ model,
218
+ input: [
219
+ {
220
+ role: "system",
221
+ content: "You answer questions using X search. Return JSON that matches the provided schema. Use citations when possible.",
222
+ },
223
+ {
224
+ role: "user",
225
+ content: parsedArgs.query,
226
+ },
227
+ ],
228
+ tools: [toolConfig],
229
+ text: {
230
+ format: {
231
+ type: "json_schema",
232
+ schema: RESPONSE_SCHEMA,
233
+ },
234
+ },
235
+ };
236
+ const response = await fetchJson(`${baseUrl}/responses`, {
237
+ method: "POST",
238
+ headers: {
239
+ "Content-Type": "application/json",
240
+ Authorization: `Bearer ${apiKey}`,
241
+ },
242
+ body: JSON.stringify(body),
243
+ }, timeoutMs);
244
+ const content = extractMessage(response.output);
245
+ const rawText = content?.text ?? "";
246
+ let parsed = { answer: rawText };
247
+ if (rawText) {
248
+ try {
249
+ const parsedJson = JSON.parse(rawText);
250
+ if (parsedJson && typeof parsedJson === "object") {
251
+ parsed = parsedJson;
252
+ }
253
+ }
254
+ catch {
255
+ // Keep raw text fallback
256
+ }
257
+ }
258
+ const normalizedCitations = normalizeCitations(content?.annotations, parsed.citations);
259
+ const normalizedResponse = {
260
+ answer: typeof parsed.answer === "string" && parsed.answer.trim().length > 0
261
+ ? parsed.answer
262
+ : rawText,
263
+ citations: normalizedCitations.citations,
264
+ inline_citations: normalizedCitations.inline_citations,
265
+ ...(parsedArgs.include_raw_response ? { raw_response: response } : {}),
266
+ };
267
+ return {
268
+ structuredContent: normalizedResponse,
269
+ content: [
270
+ {
271
+ type: "text",
272
+ text: JSON.stringify(normalizedResponse, null, 2),
273
+ },
274
+ ],
275
+ };
276
+ }
277
+ catch (error) {
278
+ const message = error instanceof Error ? error.message : "Unknown error";
279
+ console.error("x_search failed", message);
280
+ return {
281
+ content: [
282
+ {
283
+ type: "text",
284
+ text: JSON.stringify({
285
+ error: message,
286
+ status: "failed",
287
+ }, null, 2),
288
+ },
289
+ ],
290
+ isError: true,
291
+ };
292
+ }
293
+ });
294
+ async function main() {
295
+ const transport = new StdioServerTransport();
296
+ await server.connect(transport);
297
+ console.error("x-search-mcp running on stdio");
298
+ }
299
+ main().catch((error) => {
300
+ console.error("Fatal error", error);
301
+ process.exit(1);
302
+ });
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "x-search-mcp",
3
+ "version": "0.1.0",
4
+ "description": "MCP server for xAI X search via Responses API",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/konarkm/x-search-mcp.git"
10
+ },
11
+ "homepage": "https://github.com/konarkm/x-search-mcp#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/konarkm/x-search-mcp/issues"
14
+ },
15
+ "bin": {
16
+ "x-search-mcp": "bin/x-search-mcp"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "bin"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "dev": "tsx src/index.ts",
25
+ "prepublishOnly": "npm run build",
26
+ "smoke-test": "tsx scripts/smoke-test.ts",
27
+ "start": "node dist/index.js"
28
+ },
29
+ "keywords": [
30
+ "mcp",
31
+ "mcp-server",
32
+ "xai",
33
+ "x-search",
34
+ "x"
35
+ ],
36
+ "dependencies": {
37
+ "@modelcontextprotocol/sdk": "^1.18.2",
38
+ "zod": "^3.23.8"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.12.0",
42
+ "tsx": "^4.19.2",
43
+ "typescript": "^5.7.3"
44
+ },
45
+ "engines": {
46
+ "node": ">=18"
47
+ }
48
+ }