ninerouter-mcp 1.0.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,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Farhan Brillan Widyakirana (Tojoo.dev)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # NineRouter MCP
2
+
3
+ MCP server for 9Router with model discovery, automatic fallback, and type-safe validation.
4
+
5
+ ## Why this exists
6
+
7
+ 9Router already hides provider-specific complexity behind a single API. This project exposes that API through MCP so clients can use 9Router capabilities directly as native tools.
8
+
9
+ **Benefits over skill-based approaches:**
10
+ - No repeated skill file loading (saves tokens and reduces context usage)
11
+ - Tools are always available without manual skill invocation
12
+ - Automatic model fallback when primary models fail
13
+ - Type-safe validation with proper error messages
14
+ - Direct integration into MCP-native workflows
15
+
16
+ The goal is not to replace 9Router or duplicate its docs. The goal is to make 9Router capabilities immediately accessible from any MCP client.
17
+
18
+ ## What it provides
19
+
20
+ - Model discovery for choosing valid model ids
21
+ - Web search for finding current information
22
+ - Web fetch for turning URLs into readable text or markdown
23
+ - Image generation for text-to-image workflows
24
+ - Text-to-speech for voice output
25
+ - Speech-to-text for transcription
26
+ - Embeddings for retrieval and semantic search
27
+
28
+ ## When to use it
29
+
30
+ Use this server when you want an AI agent or app to work with 9Router through MCP instead of custom integration code for each capability.
31
+
32
+ It is especially useful when you want one backend that can access multiple providers but still present a single tool interface to the model.
33
+
34
+ If your client can already call MCP tools directly, you do not need separate 9Router skill docs; the MCP server becomes the integration layer.
35
+
36
+ Chat/code-gen is intentionally left out of this MCP server.
37
+
38
+ ## Installation
39
+
40
+ **Kilo CLI / VS Code**
41
+
42
+ Add to your `kilo.json`:
43
+
44
+ ```json
45
+ {
46
+ "mcp": {
47
+ "ninerouter": {
48
+ "type": "local",
49
+ "command": ["npx", "-y", "ninerouter-mcp"],
50
+ "environment": {
51
+ "NINEROUTER_URL": "http://localhost:20128"
52
+ },
53
+ "enabled": true
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ **Claude Code**
60
+
61
+ ```bash
62
+ claude mcp add --scope user ninerouter -e NINEROUTER_URL=http://localhost:20128 -- npx -y ninerouter-mcp
63
+ ```
64
+
65
+ **Codex CLI**
66
+
67
+ ```bash
68
+ codex mcp add ninerouter --env NINEROUTER_URL=http://localhost:20128 -- npx -y ninerouter-mcp
69
+ ```
70
+
71
+ **Agent Manager (VS Code Extension)**
72
+
73
+ Use the MCP settings in your workspace `kilo.json` (same as Kilo CLI above). Agent Manager automatically inherits MCP servers from Kilo config.
74
+
75
+ ## Configuration
76
+
77
+ ### Quick Setup
78
+
79
+ Create a config file with defaults:
80
+
81
+ ```bash
82
+ npx ninerouter-mcp create-config
83
+ ```
84
+
85
+ This creates `~/.config/ninerouter-mcp/config.toml` with sample configuration. Edit it to set your 9Router base URL and optionally configure default models.
86
+
87
+ ### Manual Setup
88
+
89
+ 1. Install dependencies:
90
+
91
+ ```bash
92
+ npm install
93
+ ```
94
+
95
+ 2. Configure the 9Router endpoint:
96
+
97
+ ```bash
98
+ set NINEROUTER_URL=http://localhost:20128
99
+ set NINEROUTER_KEY=sk-...
100
+ ```
101
+
102
+ `NINEROUTER_KEY` is optional when your 9Router instance does not require auth.
103
+
104
+ You can also use a config file at `~/.config/ninerouter-mcp/config.toml`.
105
+ TOML settings override environment variables.
106
+
107
+ Example:
108
+
109
+ ```toml
110
+ base_url = "http://localhost:20128"
111
+ api_key = "sk-..."
112
+
113
+ # Optional: default models with fallback support
114
+ [default_models]
115
+ web_search = ["tavily/search", "brave-search/search"]
116
+ web_fetch = "firecrawl/fetch"
117
+ generate_image = "openai/dall-e-3"
118
+ text_to_speech = "openai/tts-1"
119
+ speech_to_text = ["openai/whisper-1", "groq/whisper-large-v3-turbo"]
120
+ embeddings = "openai/text-embedding-3-small"
121
+ ```
122
+
123
+ Default models can be a single string or array of strings. When array, models are tried in order until one succeeds. If all fail, errors are aggregated.
124
+
125
+ To pass a different config file at startup, use `--config`:
126
+
127
+ ```bash
128
+ npm start -- --config D:\path\to\config.toml
129
+ ```
130
+
131
+ 3. Build the server:
132
+
133
+ ```bash
134
+ npm run build
135
+ ```
136
+
137
+ 4. Start the MCP server over stdio:
138
+
139
+ ```bash
140
+ npm start
141
+ ```
142
+
143
+ ## Run
144
+
145
+ For local development in this repo:
146
+
147
+ ```bash
148
+ npm run build
149
+ npm start
150
+ ```
151
+
152
+ If you publish the package to npm, users can run it directly with npx:
153
+
154
+ ```bash
155
+ npx -y ninerouter-mcp
156
+ ```
157
+
158
+ That works because the package exposes a `bin` entry and builds `dist/index.js` during packing.
159
+
160
+ If you want to run from the repo without publishing, use:
161
+
162
+ ```bash
163
+ npx tsx src/index.ts
164
+ ```
165
+
166
+ ## Available Tools
167
+
168
+ - `list_models`
169
+ - `web_search`
170
+ - `web_fetch`
171
+ - `generate_image`
172
+ - `text_to_speech`
173
+ - `speech_to_text`
174
+ - `embeddings`
175
+
176
+ ## Notes
177
+
178
+ - The server expects a local or reachable 9Router base URL in `NINEROUTER_URL`.
179
+ - If present, `~/.config/ninerouter-mcp/config.toml` is loaded first and wins over env vars.
180
+ - `list_models` can list default chat models or a specific capability kind like `image`, `tts`, `embedding`, `web`, `stt`, or `image-to-text`.
181
+ - STT accepts either a local `audioPath` or a base64 payload.
182
+ - Image and audio tools return JSON text, including base64 data when the upstream API returns binary content.
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile, mkdir, access } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { constants } from "node:fs";
6
+ const DEFAULT_CONFIG_DIR = join(homedir(), ".config", "ninerouter-mcp");
7
+ const DEFAULT_CONFIG_PATH = join(DEFAULT_CONFIG_DIR, "config.toml");
8
+ const DEFAULT_CONFIG = `# NineRouter MCP Configuration
9
+ # Generated on ${new Date().toISOString()}
10
+
11
+ # 9Router base URL (required)
12
+ base_url = "http://localhost:20128"
13
+
14
+ # Optional API key (if your 9Router instance requires auth)
15
+ # api_key = "sk-your-key-here"
16
+
17
+ # Optional: default models with fallback support
18
+ # Can be a single string or array of strings for fallback
19
+ # If user doesn't specify a model, these will be tried in order
20
+ [default_models]
21
+
22
+ # Web search - tries tavily first, falls back to brave if tavily fails
23
+ web_search = ["tavily/search", "brave-search/search"]
24
+
25
+ # Or use single string for just one default
26
+ # web_search = "tavily/search"
27
+
28
+ # Web fetch - tries firecrawl first, then jina-reader
29
+ web_fetch = ["firecrawl/fetch", "jina-reader/fetch"]
30
+
31
+ # Image generation
32
+ generate_image = "openai/dall-e-3"
33
+
34
+ # Text to speech
35
+ text_to_speech = "openai/tts-1"
36
+
37
+ # Speech to text - tries openai whisper, falls back to groq
38
+ speech_to_text = ["openai/whisper-1", "groq/whisper-large-v3-turbo"]
39
+
40
+ # Embeddings
41
+ embeddings = "openai/text-embedding-3-small"
42
+ `;
43
+ async function createConfig() {
44
+ try {
45
+ // Create config directory if it doesn't exist
46
+ await mkdir(DEFAULT_CONFIG_DIR, { recursive: true });
47
+ // Check if config file already exists
48
+ try {
49
+ await access(DEFAULT_CONFIG_PATH, constants.F_OK);
50
+ console.log(`⚠️ Config file already exists at: ${DEFAULT_CONFIG_PATH}`);
51
+ console.log("To avoid overwriting your config, the operation was cancelled.");
52
+ console.log("\nTo create a new config, first backup or delete the existing file.");
53
+ return;
54
+ }
55
+ catch {
56
+ // File doesn't exist, safe to create
57
+ }
58
+ // Write config file
59
+ await writeFile(DEFAULT_CONFIG_PATH, DEFAULT_CONFIG, "utf8");
60
+ console.log(`✅ Config file created at: ${DEFAULT_CONFIG_PATH}`);
61
+ console.log("\nNext steps:");
62
+ console.log("1. Edit the config file to set your 9Router base URL");
63
+ console.log("2. Optionally configure default models for each tool");
64
+ console.log("3. Restart your MCP client to load the new config");
65
+ }
66
+ catch (error) {
67
+ console.error("❌ Failed to create config file:", error);
68
+ process.exit(1);
69
+ }
70
+ }
71
+ createConfig();
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // Check if user wants to create config
2
+ if (process.argv.includes("create-config")) {
3
+ await import("./create-config.js");
4
+ }
5
+ else {
6
+ // Start MCP server
7
+ await import("./server.js");
8
+ }
9
+ export {};
@@ -0,0 +1,183 @@
1
+ import { access, readFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { parse as parseToml } from "@iarna/toml";
5
+ const DEFAULT_CONFIG_PATH = path.join(os.homedir(), ".config", "ninerouter-mcp", "config.toml");
6
+ export function getDefaultConfigPath() {
7
+ return DEFAULT_CONFIG_PATH;
8
+ }
9
+ export function resolveConfigPath(argv) {
10
+ for (let index = 2; index < argv.length; index += 1) {
11
+ const argument = argv[index];
12
+ if (argument === "--config" || argument === "--config-file" || argument === "-c") {
13
+ const nextValue = argv[index + 1];
14
+ if (!nextValue) {
15
+ throw new Error(`Missing value for ${argument}.`);
16
+ }
17
+ return nextValue;
18
+ }
19
+ if (argument.startsWith("--config=") || argument.startsWith("--config-file=")) {
20
+ return argument.slice(argument.indexOf("=") + 1);
21
+ }
22
+ }
23
+ return process.env.NINEROUTER_CONFIG?.trim() || undefined;
24
+ }
25
+ function normalizeBaseUrl(baseUrl) {
26
+ return baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
27
+ }
28
+ function pickConfigValue(configFile, key) {
29
+ const nestedValue = configFile.ninerouter?.[key];
30
+ if (typeof nestedValue === "string" && nestedValue.trim()) {
31
+ return nestedValue.trim();
32
+ }
33
+ const topLevelValue = configFile[key];
34
+ if (typeof topLevelValue === "string" && topLevelValue.trim()) {
35
+ return topLevelValue.trim();
36
+ }
37
+ return undefined;
38
+ }
39
+ async function loadConfigFile(configPath) {
40
+ try {
41
+ await access(configPath);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ const raw = await readFile(configPath, "utf8");
47
+ const parsed = parseToml(raw);
48
+ return parsed;
49
+ }
50
+ export async function getConfig(options = {}) {
51
+ const configFile = await loadConfigFile(options.configPath ?? DEFAULT_CONFIG_PATH);
52
+ const baseUrlFromFile = configFile ? pickConfigValue(configFile, "base_url") : undefined;
53
+ const apiKeyFromFile = configFile ? pickConfigValue(configFile, "api_key") : undefined;
54
+ const baseUrl = baseUrlFromFile ?? process.env.NINEROUTER_URL;
55
+ if (!baseUrl) {
56
+ throw new Error(`NINEROUTER_URL is required. Set it in ${options.configPath ?? DEFAULT_CONFIG_PATH} or as an environment variable.`);
57
+ }
58
+ const apiKey = apiKeyFromFile ?? process.env.NINEROUTER_KEY?.trim();
59
+ // Convert snake_case to camelCase and normalize string to array
60
+ const normalizeToArray = (value) => {
61
+ if (!value)
62
+ return undefined;
63
+ return Array.isArray(value) ? value : [value];
64
+ };
65
+ const defaultModels = configFile?.default_models ? {
66
+ webSearch: normalizeToArray(configFile.default_models.web_search),
67
+ webFetch: normalizeToArray(configFile.default_models.web_fetch),
68
+ generateImage: normalizeToArray(configFile.default_models.generate_image),
69
+ textToSpeech: normalizeToArray(configFile.default_models.text_to_speech),
70
+ speechToText: normalizeToArray(configFile.default_models.speech_to_text),
71
+ embeddings: normalizeToArray(configFile.default_models.embeddings),
72
+ } : undefined;
73
+ return {
74
+ baseUrl: normalizeBaseUrl(baseUrl),
75
+ apiKey: apiKey ? apiKey : undefined,
76
+ defaultModels,
77
+ };
78
+ }
79
+ function buildUrl(baseUrl, pathname, query) {
80
+ const url = new URL(pathname.replace(/^\//, ""), baseUrl);
81
+ for (const [key, value] of Object.entries(query ?? {})) {
82
+ if (value === undefined) {
83
+ continue;
84
+ }
85
+ url.searchParams.set(key, String(value));
86
+ }
87
+ return url;
88
+ }
89
+ function authHeaders(apiKey) {
90
+ return apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
91
+ }
92
+ async function readErrorMessage(response) {
93
+ const text = await response.text();
94
+ if (!text) {
95
+ return `${response.status} ${response.statusText}`;
96
+ }
97
+ try {
98
+ const parsed = JSON.parse(text);
99
+ if (typeof parsed.message === "string") {
100
+ return parsed.message;
101
+ }
102
+ if (typeof parsed.error === "string") {
103
+ return parsed.error;
104
+ }
105
+ if (parsed.error && typeof parsed.error === "object" && "message" in parsed.error) {
106
+ const message = parsed.error.message;
107
+ if (typeof message === "string") {
108
+ return message;
109
+ }
110
+ }
111
+ }
112
+ catch {
113
+ // Fall through to the raw text body.
114
+ }
115
+ return text;
116
+ }
117
+ function ensureOk(response, action) {
118
+ if (response.ok) {
119
+ return response;
120
+ }
121
+ return readErrorMessage(response).then((message) => {
122
+ throw new Error(`9Router ${action} failed with ${response.status}: ${message}`);
123
+ });
124
+ }
125
+ export async function requestJson(config, pathname, body, query) {
126
+ const response = await fetch(buildUrl(config.baseUrl, pathname, query), {
127
+ method: "POST",
128
+ headers: {
129
+ "Content-Type": "application/json",
130
+ ...authHeaders(config.apiKey),
131
+ },
132
+ body: JSON.stringify(body),
133
+ });
134
+ await ensureOk(response, pathname);
135
+ return (await response.json());
136
+ }
137
+ export async function requestGetJson(config, pathname, query) {
138
+ const response = await fetch(buildUrl(config.baseUrl, pathname, query), {
139
+ method: "GET",
140
+ headers: {
141
+ ...authHeaders(config.apiKey),
142
+ },
143
+ });
144
+ await ensureOk(response, pathname);
145
+ return (await response.json());
146
+ }
147
+ export async function requestBinary(config, pathname, body, query) {
148
+ const response = await fetch(buildUrl(config.baseUrl, pathname, query), {
149
+ method: "POST",
150
+ headers: {
151
+ "Content-Type": "application/json",
152
+ ...authHeaders(config.apiKey),
153
+ },
154
+ body: JSON.stringify(body),
155
+ });
156
+ await ensureOk(response, pathname);
157
+ const buffer = Buffer.from(await response.arrayBuffer());
158
+ return {
159
+ base64: buffer.toString("base64"),
160
+ contentType: response.headers.get("content-type"),
161
+ };
162
+ }
163
+ export async function requestMultipartText(config, pathname, formData, query) {
164
+ const response = await fetch(buildUrl(config.baseUrl, pathname, query), {
165
+ method: "POST",
166
+ headers: {
167
+ ...authHeaders(config.apiKey),
168
+ },
169
+ body: formData,
170
+ });
171
+ await ensureOk(response, pathname);
172
+ return {
173
+ text: await response.text(),
174
+ contentType: response.headers.get("content-type"),
175
+ };
176
+ }
177
+ export async function createFileBlob(filePath) {
178
+ const content = await readFile(filePath);
179
+ return new Blob([content]);
180
+ }
181
+ export function fileNameFromPath(filePath) {
182
+ return path.basename(filePath);
183
+ }
package/dist/server.js ADDED
@@ -0,0 +1,29 @@
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
3
+ import { getConfig, resolveConfigPath } from "./ninerouter-client.js";
4
+ import { registerEmbeddingTools } from "./tools/embeddings.js";
5
+ import { registerMediaTools } from "./tools/media.js";
6
+ import { registerModelTools } from "./tools/models.js";
7
+ import { registerWebTools } from "./tools/web.js";
8
+ const server = new McpServer({
9
+ name: "ninerouter-mcp",
10
+ version: "1.0.0",
11
+ }, {
12
+ capabilities: {
13
+ tools: {},
14
+ },
15
+ });
16
+ async function main() {
17
+ const configPath = resolveConfigPath(process.argv);
18
+ const config = await getConfig({ configPath });
19
+ registerModelTools(server, config);
20
+ registerWebTools(server, config);
21
+ registerMediaTools(server, config);
22
+ registerEmbeddingTools(server, config);
23
+ const transport = new StdioServerTransport();
24
+ await server.connect(transport);
25
+ }
26
+ main().catch((error) => {
27
+ console.error(error);
28
+ process.exit(1);
29
+ });
@@ -0,0 +1,26 @@
1
+ export function pickModel(model, provider) {
2
+ const selected = model ?? provider;
3
+ if (!selected) {
4
+ throw new Error("Provide either model or provider.");
5
+ }
6
+ return selected;
7
+ }
8
+ export function toPrettyJson(value) {
9
+ return JSON.stringify(value, null, 2);
10
+ }
11
+ export async function tryModelsWithFallback(models, operation) {
12
+ const errors = [];
13
+ for (const model of models) {
14
+ try {
15
+ return await operation(model);
16
+ }
17
+ catch (error) {
18
+ errors.push({
19
+ model,
20
+ error: error instanceof Error ? error.message : String(error),
21
+ });
22
+ }
23
+ }
24
+ const errorSummary = errors.map((e) => `${e.model}: ${e.error}`).join("; ");
25
+ throw new Error(`All models failed. Errors: ${errorSummary}`);
26
+ }
@@ -0,0 +1,33 @@
1
+ import { z } from "zod/v4";
2
+ import { requestJson } from "../ninerouter-client.js";
3
+ import { toPrettyJson, tryModelsWithFallback } from "./common.js";
4
+ export function registerEmbeddingTools(server, config) {
5
+ server.registerTool("embeddings", {
6
+ description: "Generate embeddings through 9Router and return the raw embedding payload.",
7
+ inputSchema: z.object({
8
+ model: z.string().optional().describe("9Router embedding model id, for example openai/text-embedding-3-small."),
9
+ provider: z.string().optional().describe("Alias for model; accepted for compatibility with 9Router docs."),
10
+ input: z.union([z.string(), z.array(z.string().min(1))]).describe("Text input or a batch of text inputs."),
11
+ encodingFormat: z.enum(["float", "base64"]).optional().default("float"),
12
+ dimensions: z.number().int().positive().optional(),
13
+ }),
14
+ }, async ({ model, provider, input, encodingFormat, dimensions }) => {
15
+ const userModel = model ?? provider;
16
+ const defaultModels = config.defaultModels?.embeddings ?? [];
17
+ const modelsToTry = userModel ? [userModel] : defaultModels;
18
+ if (modelsToTry.length === 0) {
19
+ throw new Error("No model specified and no default_models.embeddings configured.");
20
+ }
21
+ const payload = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
22
+ return await requestJson(config, "/v1/embeddings", {
23
+ model: selectedModel,
24
+ input,
25
+ encoding_format: encodingFormat,
26
+ dimensions,
27
+ });
28
+ });
29
+ return {
30
+ content: [{ type: "text", text: toPrettyJson(payload) }],
31
+ };
32
+ });
33
+ }
@@ -0,0 +1,143 @@
1
+ import { z } from "zod/v4";
2
+ import { createFileBlob, fileNameFromPath, requestBinary, requestJson, requestMultipartText } from "../ninerouter-client.js";
3
+ import { toPrettyJson, tryModelsWithFallback } from "./common.js";
4
+ export function registerMediaTools(server, config) {
5
+ server.registerTool("generate_image", {
6
+ description: "Generate an image through 9Router and return the upstream response as JSON or base64.",
7
+ inputSchema: z.object({
8
+ prompt: z.string().min(1).describe("Image prompt."),
9
+ model: z.string().optional().describe("9Router image model id, for example gemini/gemini-3-pro-image-preview or openai/dall-e-3."),
10
+ provider: z.string().optional().describe("Alias for model; accepted for compatibility with 9Router docs."),
11
+ n: z.number().int().positive().max(10).optional().default(1),
12
+ size: z.string().optional().default("1024x1024"),
13
+ quality: z.enum(["standard", "hd"]).optional(),
14
+ responseFormat: z.enum(["url", "b64_json", "binary"]).optional().default("url"),
15
+ }),
16
+ }, async ({ prompt, model, provider, n, size, quality, responseFormat }) => {
17
+ const userModel = model ?? provider;
18
+ const defaultModels = config.defaultModels?.generateImage ?? [];
19
+ const modelsToTry = userModel ? [userModel] : defaultModels;
20
+ if (modelsToTry.length === 0) {
21
+ throw new Error("No model specified and no default_models.generate_image configured.");
22
+ }
23
+ if (responseFormat === "binary") {
24
+ const binary = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
25
+ return await requestBinary(config, "/v1/images/generations", {
26
+ model: selectedModel,
27
+ prompt,
28
+ n,
29
+ size,
30
+ quality,
31
+ }, {
32
+ response_format: "binary",
33
+ });
34
+ });
35
+ return {
36
+ content: [{ type: "text", text: toPrettyJson({ contentType: binary.contentType, base64: binary.base64 }) }],
37
+ };
38
+ }
39
+ const payload = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
40
+ return await requestJson(config, "/v1/images/generations", {
41
+ model: selectedModel,
42
+ prompt,
43
+ n,
44
+ size,
45
+ quality,
46
+ response_format: responseFormat,
47
+ });
48
+ });
49
+ return {
50
+ content: [{ type: "text", text: toPrettyJson(payload) }],
51
+ };
52
+ });
53
+ server.registerTool("text_to_speech", {
54
+ description: "Convert text to speech through 9Router and return base64-encoded audio.",
55
+ inputSchema: z.object({
56
+ input: z.string().min(1).describe("Text to synthesize."),
57
+ model: z.string().optional().describe("9Router TTS model or voice id, for example openai/tts-1 or edge-tts/vi-VN-HoaiMyNeural."),
58
+ provider: z.string().optional().describe("Alias for model; accepted for compatibility with 9Router docs."),
59
+ responseFormat: z.enum(["json", "mp3"]).optional().default("json"),
60
+ }),
61
+ }, async ({ input, model, provider, responseFormat }) => {
62
+ const userModel = model ?? provider;
63
+ const defaultModels = config.defaultModels?.textToSpeech ?? [];
64
+ const modelsToTry = userModel ? [userModel] : defaultModels;
65
+ if (modelsToTry.length === 0) {
66
+ throw new Error("No model specified and no default_models.text_to_speech configured.");
67
+ }
68
+ if (responseFormat === "mp3") {
69
+ const binary = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
70
+ return await requestBinary(config, "/v1/audio/speech", {
71
+ model: selectedModel,
72
+ input,
73
+ }, {
74
+ response_format: "mp3",
75
+ });
76
+ });
77
+ return {
78
+ content: [{ type: "text", text: toPrettyJson({ contentType: binary.contentType, audioBase64: binary.base64, format: "mp3" }) }],
79
+ };
80
+ }
81
+ const payload = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
82
+ return await requestJson(config, "/v1/audio/speech", {
83
+ model: selectedModel,
84
+ input,
85
+ }, {
86
+ response_format: "json",
87
+ });
88
+ });
89
+ return {
90
+ content: [{ type: "text", text: toPrettyJson(payload) }],
91
+ };
92
+ });
93
+ server.registerTool("speech_to_text", {
94
+ description: "Transcribe audio through 9Router using a local file path or a base64 payload.",
95
+ inputSchema: z.object({
96
+ model: z.string().optional().describe("9Router STT model id, for example openai/whisper-1 or groq/whisper-large-v3-turbo."),
97
+ provider: z.string().optional().describe("Alias for model; accepted for compatibility with 9Router docs."),
98
+ audioPath: z.string().optional().describe("Local path to an audio file."),
99
+ audioBase64: z.string().optional().describe("Base64-encoded audio payload."),
100
+ fileName: z.string().optional().describe("File name to use when uploading a base64 payload."),
101
+ language: z.string().optional().describe("Optional ISO-639-1 language code, for example en or vi."),
102
+ prompt: z.string().optional(),
103
+ responseFormat: z.enum(["json", "text", "verbose_json", "srt", "vtt"]).optional().default("json"),
104
+ temperature: z.number().min(0).max(1).optional(),
105
+ }).refine((value) => Boolean(value.audioPath || value.audioBase64), {
106
+ message: "Provide audioPath or audioBase64.",
107
+ }),
108
+ }, async ({ model, provider, audioPath, audioBase64, fileName, language, prompt, responseFormat, temperature }) => {
109
+ const userModel = model ?? provider;
110
+ const defaultModels = config.defaultModels?.speechToText ?? [];
111
+ const modelsToTry = userModel ? [userModel] : defaultModels;
112
+ if (modelsToTry.length === 0) {
113
+ throw new Error("No model specified and no default_models.speech_to_text configured.");
114
+ }
115
+ const payload = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
116
+ const formData = new FormData();
117
+ formData.append("model", selectedModel);
118
+ if (audioPath) {
119
+ const blob = await createFileBlob(audioPath);
120
+ formData.append("file", blob, fileName ?? fileNameFromPath(audioPath));
121
+ }
122
+ else if (audioBase64) {
123
+ const blob = new Blob([Buffer.from(audioBase64, "base64")]);
124
+ formData.append("file", blob, fileName ?? "audio.bin");
125
+ }
126
+ if (language) {
127
+ formData.append("language", language);
128
+ }
129
+ if (prompt) {
130
+ formData.append("prompt", prompt);
131
+ }
132
+ if (temperature !== undefined) {
133
+ formData.append("temperature", String(temperature));
134
+ }
135
+ return await requestMultipartText(config, "/v1/audio/transcriptions", formData, {
136
+ response_format: responseFormat,
137
+ });
138
+ });
139
+ return {
140
+ content: [{ type: "text", text: payload.text }],
141
+ };
142
+ });
143
+ }
@@ -0,0 +1,19 @@
1
+ import { z } from "zod/v4";
2
+ import { requestGetJson } from "../ninerouter-client.js";
3
+ import { toPrettyJson } from "./common.js";
4
+ const MODEL_KINDS = ["chat", "image", "tts", "embedding", "web", "stt", "image-to-text"];
5
+ export function registerModelTools(server, config) {
6
+ server.registerTool("list_models", {
7
+ description: "List available 9Router models. Call this first to choose a valid model id before using any other 9Router tool.",
8
+ inputSchema: z.object({
9
+ kind: z.enum(MODEL_KINDS).optional().describe("Optional model category. Omit to list default chat models."),
10
+ }),
11
+ }, async ({ kind }) => {
12
+ const payload = kind
13
+ ? await requestGetJson(config, `/v1/models/${kind}`)
14
+ : await requestGetJson(config, "/v1/models");
15
+ return {
16
+ content: [{ type: "text", text: toPrettyJson(payload) }],
17
+ };
18
+ });
19
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from "zod/v4";
2
+ import { requestJson } from "../ninerouter-client.js";
3
+ import { toPrettyJson, tryModelsWithFallback } from "./common.js";
4
+ export function registerWebTools(server, config) {
5
+ server.registerTool("web_search", {
6
+ description: "Search the web through 9Router and return the raw search payload.",
7
+ inputSchema: z.object({
8
+ query: z.string().min(1).describe("Search query to send to 9Router."),
9
+ model: z.string().optional().describe("9Router web-search model id, for example tavily/search or brave-search/search."),
10
+ provider: z.string().optional().describe("Alias for model; accepted for compatibility with 9Router docs."),
11
+ maxResults: z.number().int().positive().max(20).optional().default(5),
12
+ searchType: z.enum(["web", "news"]).optional().default("web"),
13
+ country: z.string().optional(),
14
+ language: z.string().optional(),
15
+ timeRange: z.string().optional(),
16
+ domainFilter: z.string().optional(),
17
+ }),
18
+ }, async ({ query, model, provider, maxResults, searchType, country, language, timeRange, domainFilter }) => {
19
+ const userModel = model ?? provider;
20
+ const defaultModels = config.defaultModels?.webSearch ?? [];
21
+ const modelsToTry = userModel ? [userModel] : defaultModels;
22
+ if (modelsToTry.length === 0) {
23
+ throw new Error("No model specified and no default_models.web_search configured.");
24
+ }
25
+ const payload = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
26
+ return await requestJson(config, "/v1/search", {
27
+ model: selectedModel,
28
+ query,
29
+ max_results: maxResults,
30
+ search_type: searchType,
31
+ country,
32
+ language,
33
+ time_range: timeRange,
34
+ domain_filter: domainFilter,
35
+ });
36
+ });
37
+ return {
38
+ content: [{ type: "text", text: toPrettyJson(payload) }],
39
+ };
40
+ });
41
+ server.registerTool("web_fetch", {
42
+ description: "Fetch a URL through 9Router and return markdown, text, or HTML extraction output.",
43
+ inputSchema: z.object({
44
+ url: z.string().url().describe("URL to fetch and extract."),
45
+ model: z.string().optional().describe("9Router web-fetch model id, for example jina-reader/fetch or firecrawl/fetch."),
46
+ provider: z.string().optional().describe("Alias for model; accepted for compatibility with 9Router docs."),
47
+ format: z.enum(["markdown", "text", "html"]).optional().default("markdown"),
48
+ maxCharacters: z.number().int().nonnegative().optional().default(8000),
49
+ }),
50
+ }, async ({ url, model, provider, format, maxCharacters }) => {
51
+ const userModel = model ?? provider;
52
+ const defaultModels = config.defaultModels?.webFetch ?? [];
53
+ const modelsToTry = userModel ? [userModel] : defaultModels;
54
+ if (modelsToTry.length === 0) {
55
+ throw new Error("No model specified and no default_models.web_fetch configured.");
56
+ }
57
+ const payload = await tryModelsWithFallback(modelsToTry, async (selectedModel) => {
58
+ return await requestJson(config, "/v1/web/fetch", {
59
+ model: selectedModel,
60
+ url,
61
+ format,
62
+ max_characters: maxCharacters,
63
+ });
64
+ });
65
+ return {
66
+ content: [{ type: "text", text: toPrettyJson(payload) }],
67
+ };
68
+ });
69
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "ninerouter-mcp",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "MCP server for 9Router with model discovery, automatic fallback, and type-safe validation",
6
+ "license": "Apache-2.0",
7
+ "author": "Farhan Brillan Widyakirana <https://tojoo.dev>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/k1rana/ninerouter-mcp.git"
11
+ },
12
+ "keywords": [
13
+ "9router",
14
+ "mcp",
15
+ "model-context-protocol",
16
+ "ai",
17
+ "llm",
18
+ "tools",
19
+ "web-search",
20
+ "embeddings",
21
+ "tts",
22
+ "stt",
23
+ "image-generation"
24
+ ],
25
+ "homepage": "https://github.com/k1rana/ninerouter-mcp#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/k1rana/ninerouter-mcp/issues"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "bin": {
35
+ "ninerouter-mcp": "dist/index.js"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.json",
39
+ "prepack": "npm run build",
40
+ "start": "node dist/index.js",
41
+ "dev": "tsx watch src/index.ts",
42
+ "create-config": "tsx src/create-config.ts"
43
+ },
44
+ "dependencies": {
45
+ "@modelcontextprotocol/server": "^2.0.0-beta.2",
46
+ "@iarna/toml": "^2.2.5",
47
+ "zod": "^4.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^22.0.0",
51
+ "tsx": "^4.19.0",
52
+ "typescript": "^5.6.0"
53
+ }
54
+ }