@stabgan/openrouter-mcp-multimodal 3.1.1 → 4.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 CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 stabgan
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.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  <a href="https://www.npmjs.com/package/@stabgan/openrouter-mcp-multimodal"><img src="https://img.shields.io/npm/v/@stabgan/openrouter-mcp-multimodal.svg?label=npm&color=cb3837&logo=npm" alt="npm version" /></a>
13
13
  <a href="https://hub.docker.com/r/stabgan/openrouter-mcp-multimodal"><img src="https://img.shields.io/docker/v/stabgan/openrouter-mcp-multimodal/latest?label=docker&color=2496ed&logo=docker&logoColor=white" alt="Docker version" /></a>
14
14
  <a href="https://github.com/stabgan/openrouter-mcp-multimodal/actions/workflows/publish.yml"><img src="https://github.com/stabgan/openrouter-mcp-multimodal/actions/workflows/publish.yml/badge.svg" alt="CI" /></a>
15
- <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="MIT" /></a>
15
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" alt="Apache 2.0" /></a>
16
16
  <a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-%E2%89%A518-43853d?logo=node.js&logoColor=white" alt="Node.js" /></a>
17
17
  </p>
18
18
 
@@ -20,6 +20,7 @@
20
20
  <a href="https://www.npmjs.com/package/@stabgan/openrouter-mcp-multimodal"><img src="https://img.shields.io/npm/dt/@stabgan/openrouter-mcp-multimodal.svg?label=npm%20downloads&color=cb3837&logo=npm" alt="npm downloads" /></a>
21
21
  <a href="https://www.npmjs.com/package/@stabgan/openrouter-mcp-multimodal"><img src="https://img.shields.io/npm/dm/@stabgan/openrouter-mcp-multimodal.svg?label=monthly&color=cb3837&logo=npm" alt="npm monthly" /></a>
22
22
  <a href="https://hub.docker.com/r/stabgan/openrouter-mcp-multimodal"><img src="https://img.shields.io/docker/pulls/stabgan/openrouter-mcp-multimodal.svg?label=docker%20pulls&color=2496ed&logo=docker&logoColor=white" alt="Docker pulls" /></a>
23
+ <a href="https://smithery.ai/servers/stabgan/openrouter-mcp-multimodal"><img src="https://smithery.ai/badge/stabgan/openrouter-mcp-multimodal" alt="Smithery" /></a>
23
24
  <a href="https://github.com/stabgan/openrouter-mcp-multimodal/stargazers"><img src="https://img.shields.io/github/stars/stabgan/openrouter-mcp-multimodal.svg?style=social" alt="GitHub stars" /></a>
24
25
  <a href="https://github.com/stabgan/openrouter-mcp-multimodal/network/members"><img src="https://img.shields.io/github/forks/stabgan/openrouter-mcp-multimodal.svg?style=social" alt="GitHub forks" /></a>
25
26
  </p>
@@ -105,7 +106,7 @@ Install-link audit (2026-04-20, round 4 — HTTPS redirectors only):
105
106
 
106
107
  | Tool | Description |
107
108
  | :--- | :--- |
108
- | `chat_completion` | Send messages to any OpenRouter model. Detects reasoning-model cutoffs. |
109
+ | `chat_completion` | Send messages to any OpenRouter model. Detects reasoning-model cutoffs. Supports **provider routing** (`quantizations`, `ignore`, `sort`, `order`, `require_parameters`, `data_collection`, `allow_fallbacks`) and **model suffixes** (`:nitro` for fastest, `:floor` for cheapest). |
109
110
  | `analyze_image` | Analyze images from local files, URLs, or data URIs. Auto-optimized with sharp. |
110
111
  | `analyze_audio` | Analyze/transcribe audio (WAV, MP3, FLAC, OGG, etc.) from files, URLs, or data URIs. |
111
112
  | `analyze_video` | Analyze/transcribe video (mp4, mpeg, mov, webm) from files, URLs, or data URIs. |
@@ -191,6 +192,14 @@ npx -y @smithery/cli install @stabgan/openrouter-mcp-multimodal --client claude
191
192
  | `OPENROUTER_API_KEY` | Yes | — | Your OpenRouter API key |
192
193
  | `OPENROUTER_DEFAULT_MODEL` | No | `nvidia/nemotron-nano-12b-v2-vl:free` | Default model for chat + analyze tools |
193
194
  | `DEFAULT_MODEL` | No | — | Alias for above |
195
+ | `OPENROUTER_MAX_TOKENS` | No | — | Default `max_tokens` for `chat_completion` when not set in the request. Useful on low-credit / free-tier accounts to avoid the full-context-window reservation. |
196
+ | `OPENROUTER_PROVIDER_QUANTIZATIONS` | No | — | CSV. Filter providers by quantization (e.g. `fp16,int8`). |
197
+ | `OPENROUTER_PROVIDER_IGNORE` | No | — | CSV. Exclude these provider slugs (e.g. `openai,anthropic`). |
198
+ | `OPENROUTER_PROVIDER_SORT` | No | — | `price` / `throughput` / `latency`. |
199
+ | `OPENROUTER_PROVIDER_ORDER` | No | — | JSON array or CSV of provider IDs (e.g. `["meta-llama","google"]`). |
200
+ | `OPENROUTER_PROVIDER_REQUIRE_PARAMETERS` | No | — | `true` / `false`. Only use providers supporting every request parameter. |
201
+ | `OPENROUTER_PROVIDER_DATA_COLLECTION` | No | — | `allow` / `deny`. Opt out of providers that log request data. |
202
+ | `OPENROUTER_PROVIDER_ALLOW_FALLBACKS` | No | — | `true` / `false`. |
194
203
  | `OPENROUTER_MODEL_CACHE_TTL_MS` | No | `3600000` | Model cache TTL (ms) |
195
204
  | `OPENROUTER_IMAGE_MAX_DIMENSION` | No | `800` | Longest edge for resize (px) |
196
205
  | `OPENROUTER_IMAGE_JPEG_QUALITY` | No | `80` | JPEG quality (1–100) |
@@ -230,6 +239,16 @@ npx -y @smithery/cli install @stabgan/openrouter-mcp-multimodal --client claude
230
239
  # Chat
231
240
  Use chat_completion to explain quantum computing in simple terms.
232
241
 
242
+ # Chat with provider routing — prefer cheapest provider, exclude OpenAI, opt out of data collection
243
+ Use chat_completion with model "anthropic/claude-3.5-sonnet", prompt "Summarize this",
244
+ provider { sort: "price", ignore: ["openai"], data_collection: "deny" }
245
+
246
+ # Chat with :nitro variant for faster response
247
+ Use chat_completion with model "openai/gpt-4o:nitro", prompt "Reason step-by-step about this problem"
248
+
249
+ # Chat with :floor variant for cheapest provider of the requested model
250
+ Use chat_completion with model "mistralai/mistral-7b-instruct:floor", prompt "Quick check"
251
+
233
252
  # Vision
234
253
  Use analyze_image on /path/to/photo.jpg and tell me what you see.
235
254
 
@@ -320,7 +339,7 @@ Works with any MCP client: [Kiro](https://kiro.dev) · [Claude Desktop](https://
320
339
 
321
340
  ## License
322
341
 
323
- MIT
342
+ Apache 2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE). v1.0.0 through v3.2.0 were released under MIT; v4.0.0 relicensed to Apache 2.0 (Apache 2.0 is a permissive superset of MIT with explicit patent grant).
324
343
 
325
344
  ## Contributing
326
345
 
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ if (!apiKey) {
21
21
  process.exit(1);
22
22
  }
23
23
  const defaultModel = process.env.OPENROUTER_DEFAULT_MODEL || process.env.DEFAULT_MODEL || DEFAULT_MODEL;
24
- const server = new Server({ name: 'openrouter-multimodal-server', version: '3.1.1' }, { capabilities: { tools: {} } });
24
+ const server = new Server({ name: 'openrouter-multimodal-server', version: '4.0.0' }, { capabilities: { tools: {} } });
25
25
  server.onerror = (error) => console.error('[MCP Error]', error);
26
26
  new ToolHandlers(server, apiKey, defaultModel);
27
27
  process.on('SIGINT', async () => {
@@ -1,10 +1,17 @@
1
1
  import OpenAI from 'openai';
2
2
  import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions.js';
3
+ import { type ProviderRoutingOptions } from './provider-routing.js';
3
4
  export interface ChatCompletionToolRequest {
4
5
  model?: string;
5
6
  messages: ChatCompletionMessageParam[];
6
7
  temperature?: number;
7
8
  max_tokens?: number;
9
+ /**
10
+ * OpenRouter provider routing overrides. Merges on top of the
11
+ * `OPENROUTER_PROVIDER_*` env-var defaults. See
12
+ * https://openrouter.ai/docs/features/provider-routing
13
+ */
14
+ provider?: ProviderRoutingOptions;
8
15
  }
9
16
  export declare function handleChatCompletion(request: {
10
17
  params: {
@@ -1,21 +1,32 @@
1
1
  import { ErrorCode, toolError } from '../errors.js';
2
2
  import { classifyUpstreamError } from './openrouter-errors.js';
3
3
  import { extractCompletionText, detectReasoningCutoff, toUsageMeta, } from './completion-utils.js';
4
+ import { readProviderDefaults, mergeProviderOptions, buildProviderBody, resolveMaxTokens, } from './provider-routing.js';
5
+ const DEFAULT_MODEL = 'nvidia/nemotron-nano-12b-v2-vl:free';
4
6
  export async function handleChatCompletion(request, openai, defaultModel) {
5
- const { messages, model, temperature, max_tokens } = request.params.arguments ?? {
7
+ const { messages, model, temperature, max_tokens, provider } = request.params.arguments ?? {
6
8
  messages: [],
7
9
  };
8
10
  if (!messages?.length) {
9
11
  return toolError(ErrorCode.INVALID_INPUT, 'Messages array cannot be empty.');
10
12
  }
13
+ const providerOptions = mergeProviderOptions(readProviderDefaults(), provider);
14
+ const providerBody = buildProviderBody(providerOptions);
15
+ const effectiveMaxTokens = resolveMaxTokens(max_tokens);
16
+ // Build the request body. `provider` is an OpenRouter extension not in
17
+ // the OpenAI SDK's types, so we cast to unknown to thread it through.
18
+ const body = {
19
+ model: model || defaultModel || DEFAULT_MODEL,
20
+ messages,
21
+ temperature: temperature ?? 1,
22
+ };
23
+ if (typeof effectiveMaxTokens === 'number')
24
+ body.max_tokens = effectiveMaxTokens;
25
+ if (providerBody)
26
+ body.provider = providerBody;
11
27
  let completion;
12
28
  try {
13
- completion = await openai.chat.completions.create({
14
- model: model || defaultModel || 'nvidia/nemotron-nano-12b-v2-vl:free',
15
- messages,
16
- temperature: temperature ?? 1,
17
- ...(max_tokens && { max_tokens }),
18
- });
29
+ completion = (await openai.chat.completions.create(body));
19
30
  }
20
31
  catch (err) {
21
32
  return classifyUpstreamError(err);
@@ -6,7 +6,7 @@ export interface GenerateImageToolRequest {
6
6
  /**
7
7
  * Output aspect ratio. Passed through as `image_config.aspect_ratio`.
8
8
  * Supported by OpenRouter image models (e.g. `1:1`, `16:9`, `9:16`,
9
- * `4:3`, `3:4`, `21:9`). Model-dependent unsupported values fall back
9
+ * `4:3`, `3:4`, `21:9`). Model-dependent. Unsupported values fall back
10
10
  * to the model's default. See
11
11
  * https://openrouter.ai/docs/guides/overview/multimodal/image-generation
12
12
  */
@@ -25,6 +25,27 @@ export interface GenerateImageToolRequest {
25
25
  * for the image payload + any caption.
26
26
  */
27
27
  max_tokens?: number;
28
+ /**
29
+ * Optional reference images. Each entry is one of:
30
+ * - a `data:image/...;base64,...` URL,
31
+ * - an `http(s)://` URL (OpenRouter fetches it),
32
+ * - a local file path (sandboxed to `OPENROUTER_INPUT_DIR` /
33
+ * `OPENROUTER_OUTPUT_DIR` / cwd, read + base64-encoded by the server).
34
+ *
35
+ * When provided, the user message becomes multimodal: a text prompt
36
+ * plus one `image_url` block per reference, in array order. Enables
37
+ * character / style consistency and image-to-image refinement on
38
+ * chat-image models that accept image inputs (Gemini Nano Banana,
39
+ * `openai/gpt-5.4-image-2`).
40
+ */
41
+ input_images?: string[];
42
+ /**
43
+ * Override the default `modalities: ["image","text"]` sent to
44
+ * OpenRouter. Most callers should leave this unset. Provide e.g.
45
+ * `["text"]` to suppress image output for inspection / captioning,
46
+ * or other shapes for future model variants.
47
+ */
48
+ modalities?: string[];
28
49
  }
29
50
  export declare function handleGenerateImage(request: {
30
51
  params: {
@@ -66,3 +87,12 @@ export declare function handleGenerateImage(request: {
66
87
  mime: string;
67
88
  };
68
89
  }>;
90
+ /**
91
+ * Resolve a caller-supplied input image into a URL the chat-completions
92
+ * API accepts. Local file paths are sandboxed to the workspace root
93
+ * (`OPENROUTER_INPUT_DIR` or `OPENROUTER_OUTPUT_DIR` or cwd) and inlined
94
+ * as base64 data URLs.
95
+ */
96
+ export declare function resolveInputImage(ref: string): Promise<string>;
97
+ export declare function mimeFromExt(ext: string): string | null;
98
+ export declare function buildUserContent(prompt: string, inputImages?: string[]): Promise<string | OpenAI.Chat.Completions.ChatCompletionContentPart[]>;
@@ -1,4 +1,5 @@
1
1
  import { promises as fs } from 'fs';
2
+ import path from 'node:path';
2
3
  import { resolveSafeOutputPath, UnsafeOutputPathError } from './path-safety.js';
3
4
  import { parseBase64DataUrl } from './fetch-utils.js';
4
5
  import { ErrorCode, toolError, toolErrorFrom } from '../errors.js';
@@ -25,7 +26,7 @@ const VALID_ASPECT_RATIOS = new Set([
25
26
  ]);
26
27
  const VALID_IMAGE_SIZES = new Set(['0.5K', '1K', '2K', '4K']);
27
28
  export async function handleGenerateImage(request, openai) {
28
- const { prompt, model, save_path, aspect_ratio, image_size, max_tokens } = request.params.arguments ?? { prompt: '' };
29
+ const { prompt, model, save_path, aspect_ratio, image_size, max_tokens, input_images, modalities, } = request.params.arguments ?? { prompt: '' };
29
30
  if (!prompt?.trim()) {
30
31
  return toolError(ErrorCode.INVALID_INPUT, 'prompt is required.');
31
32
  }
@@ -50,9 +51,24 @@ export async function handleGenerateImage(request, openai) {
50
51
  return toolErrorFrom(ErrorCode.INTERNAL, err);
51
52
  }
52
53
  }
53
- // Assemble the request body. OpenRouter's image-generation guide requires
54
- // - `modalities: ["image", "text"]` so multimodal models (like Gemini)
55
- // know to emit an image, not just text;
54
+ // Build the user message. With no `input_images`, this is the original
55
+ // string content; with refs, it becomes a multimodal
56
+ // ChatCompletionContentPart[] (text preamble + one image_url per ref).
57
+ let content;
58
+ try {
59
+ content = await buildUserContent(prompt, input_images);
60
+ }
61
+ catch (err) {
62
+ if (err instanceof UnsafeOutputPathError) {
63
+ return toolErrorFrom(ErrorCode.UNSAFE_PATH, err);
64
+ }
65
+ return toolErrorFrom(ErrorCode.INVALID_INPUT, err, 'input_images');
66
+ }
67
+ // Assemble the request body. OpenRouter's image-generation guide
68
+ // requires:
69
+ // - `modalities: ["image", "text"]` so multimodal models (like
70
+ // Gemini) know to emit an image, not just text. Caller can
71
+ // override via the `modalities` field.
56
72
  // - `image_config.{aspect_ratio, image_size}` for shape control.
57
73
  // The OpenAI SDK doesn't type these fields, but passes unknown members
58
74
  // through to the server, so we attach them via a typed cast.
@@ -63,8 +79,8 @@ export async function handleGenerateImage(request, openai) {
63
79
  imageConfig.image_size = image_size;
64
80
  const body = {
65
81
  model: model || DEFAULT_MODEL,
66
- messages: [{ role: 'user', content: `Generate an image: ${prompt}` }],
67
- modalities: ['image', 'text'],
82
+ messages: [{ role: 'user', content }],
83
+ modalities: modalities && modalities.length ? modalities : ['image', 'text'],
68
84
  };
69
85
  if (Object.keys(imageConfig).length > 0)
70
86
  body.image_config = imageConfig;
@@ -89,8 +105,8 @@ export async function handleGenerateImage(request, openai) {
89
105
  if (!base64) {
90
106
  // Model talked but did not emit an image. Surface this as a distinct
91
107
  // condition so callers don't treat chatter as a successful image.
92
- const content = message.content;
93
- const text = typeof content === 'string' ? content : JSON.stringify(content);
108
+ const messageContent = message.content;
109
+ const text = typeof messageContent === 'string' ? messageContent : JSON.stringify(messageContent);
94
110
  return toolError(ErrorCode.UPSTREAM_REFUSED, `Model returned no image. Text response: ${text.slice(0, 300)}`, {
95
111
  reason: 'no_image_in_response',
96
112
  finish_reason: completion.choices[0]?.finish_reason,
@@ -141,6 +157,91 @@ export async function handleGenerateImage(request, openai) {
141
157
  },
142
158
  };
143
159
  }
160
+ /**
161
+ * Resolve a caller-supplied input image into a URL the chat-completions
162
+ * API accepts. Local file paths are sandboxed to the workspace root
163
+ * (`OPENROUTER_INPUT_DIR` or `OPENROUTER_OUTPUT_DIR` or cwd) and inlined
164
+ * as base64 data URLs.
165
+ */
166
+ export async function resolveInputImage(ref) {
167
+ const trimmed = ref.trim();
168
+ if (!trimmed)
169
+ throw new Error('empty input_images entry');
170
+ if (trimmed.startsWith('data:'))
171
+ return trimmed;
172
+ if (/^https?:\/\//i.test(trimmed))
173
+ return trimmed;
174
+ const root = path.resolve(process.env.OPENROUTER_INPUT_DIR || process.env.OPENROUTER_OUTPUT_DIR || process.cwd());
175
+ const unsafe = process.env.OPENROUTER_ALLOW_UNSAFE_PATHS === '1' ||
176
+ process.env.OPENROUTER_ALLOW_UNSAFE_PATHS?.toLowerCase() === 'true';
177
+ // Realpath the root first so absolute paths the caller already gave in
178
+ // canonical form (e.g. /private/var/...) and paths we resolve against
179
+ // the root (which may go through /var/... symlinks on macOS) live in
180
+ // the same namespace for the prefix check below.
181
+ const rootReal = await fs.realpath(root).catch(() => root);
182
+ const abs = path.isAbsolute(trimmed)
183
+ ? path.resolve(trimmed)
184
+ : path.resolve(rootReal, trimmed);
185
+ if (!unsafe) {
186
+ const withSep = rootReal.endsWith(path.sep) ? rootReal : rootReal + path.sep;
187
+ // Prefer realpath for the prefix check so callers can pass paths
188
+ // through symlinks (e.g. macOS `/var/...` → `/private/var/...`)
189
+ // without us rejecting them. If the file doesn't exist yet, fall
190
+ // back to a textual check on the resolved path so traversal
191
+ // (`../escape.png`) is still rejected with the right error type
192
+ // instead of leaking an ENOENT to the caller.
193
+ let canonical;
194
+ try {
195
+ canonical = await fs.realpath(abs);
196
+ }
197
+ catch {
198
+ canonical = abs;
199
+ }
200
+ if (!(canonical === rootReal || canonical.startsWith(withSep))) {
201
+ throw new UnsafeOutputPathError(`input_images entry resolves outside workspace root (${rootReal}): ${ref}`);
202
+ }
203
+ }
204
+ const buf = await fs.readFile(abs);
205
+ const mime = mimeFromExt(path.extname(abs)) || 'image/png';
206
+ return `data:${mime};base64,${buf.toString('base64')}`;
207
+ }
208
+ export function mimeFromExt(ext) {
209
+ const e = ext.toLowerCase().replace(/^\./, '');
210
+ switch (e) {
211
+ case 'png':
212
+ return 'image/png';
213
+ case 'jpg':
214
+ case 'jpeg':
215
+ return 'image/jpeg';
216
+ case 'webp':
217
+ return 'image/webp';
218
+ case 'gif':
219
+ return 'image/gif';
220
+ default:
221
+ return null;
222
+ }
223
+ }
224
+ export async function buildUserContent(prompt, inputImages) {
225
+ if (!inputImages?.length) {
226
+ return `Generate an image: ${prompt}`;
227
+ }
228
+ const parts = [
229
+ {
230
+ type: 'text',
231
+ text: `Generate an image based on this prompt, using the following reference image(s) ` +
232
+ `for visual consistency. Match the appearance, identity, and style of the references ` +
233
+ `closely; do not alter them.\n\nPrompt: ${prompt}`,
234
+ },
235
+ ];
236
+ for (const ref of inputImages) {
237
+ const url = await resolveInputImage(ref);
238
+ parts.push({
239
+ type: 'image_url',
240
+ image_url: { url, detail: 'high' },
241
+ });
242
+ }
243
+ return parts;
244
+ }
144
245
  function extractBase64(message) {
145
246
  const images = message.images;
146
247
  if (Array.isArray(images) && images.length) {
@@ -0,0 +1,53 @@
1
+ /**
2
+ * OpenRouter provider routing. Merges caller-supplied `provider` args on
3
+ * top of env-var defaults and emits the `provider` object that goes into
4
+ * `POST /chat/completions`. See
5
+ * https://openrouter.ai/docs/features/provider-routing for the spec.
6
+ *
7
+ * Precedence: explicit tool arg > env var > unset. Empty arrays / empty
8
+ * objects are dropped so we don't send noise to the API.
9
+ */
10
+ export type ProviderSort = 'price' | 'throughput' | 'latency';
11
+ export type DataCollectionPolicy = 'allow' | 'deny';
12
+ export interface ProviderRoutingOptions {
13
+ /** Filter providers by quantization (e.g. `['fp16', 'int8']`). */
14
+ quantizations?: string[];
15
+ /** Exclude these provider slugs (e.g. `['openai', 'anthropic']`). */
16
+ ignore?: string[];
17
+ /** Sort providers by this criterion. */
18
+ sort?: ProviderSort;
19
+ /** Prioritized provider list (e.g. `['openai/gpt-4o', 'anthropic/claude-3-opus']`). */
20
+ order?: string[];
21
+ /** Only use providers that support every parameter in the request. */
22
+ require_parameters?: boolean;
23
+ /** Whether providers may collect request data. */
24
+ data_collection?: DataCollectionPolicy;
25
+ /** Allow fallback to unlisted providers when preferred ones fail. */
26
+ allow_fallbacks?: boolean;
27
+ }
28
+ /**
29
+ * Read provider routing defaults from `OPENROUTER_PROVIDER_*` env vars.
30
+ * Invalid values are silently dropped (never throw at server start).
31
+ */
32
+ export declare function readProviderDefaults(): ProviderRoutingOptions;
33
+ /**
34
+ * Merge caller overrides on top of env defaults. Explicit `undefined`
35
+ * values in the override drop back to the default (they don't erase it);
36
+ * to actually erase a field, pass `null`.
37
+ */
38
+ export declare function mergeProviderOptions(defaults: ProviderRoutingOptions, overrides?: ProviderRoutingOptions): ProviderRoutingOptions;
39
+ /**
40
+ * Build the OpenRouter `provider` request-body field from options.
41
+ * Returns `undefined` when nothing is set so we don't send `{}`.
42
+ */
43
+ export declare function buildProviderBody(opts: ProviderRoutingOptions): Record<string, unknown> | undefined;
44
+ /**
45
+ * Read the default `max_tokens` from `OPENROUTER_MAX_TOKENS` env var.
46
+ * Invalid or non-positive values are ignored.
47
+ */
48
+ export declare function readDefaultMaxTokens(): number | undefined;
49
+ /**
50
+ * Resolve the effective `max_tokens` for a request. Request value wins
51
+ * over env default.
52
+ */
53
+ export declare function resolveMaxTokens(requested?: number): number | undefined;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * OpenRouter provider routing. Merges caller-supplied `provider` args on
3
+ * top of env-var defaults and emits the `provider` object that goes into
4
+ * `POST /chat/completions`. See
5
+ * https://openrouter.ai/docs/features/provider-routing for the spec.
6
+ *
7
+ * Precedence: explicit tool arg > env var > unset. Empty arrays / empty
8
+ * objects are dropped so we don't send noise to the API.
9
+ */
10
+ function parseCsv(raw) {
11
+ if (!raw)
12
+ return undefined;
13
+ const arr = raw
14
+ .split(',')
15
+ .map((s) => s.trim())
16
+ .filter((s) => s.length > 0);
17
+ return arr.length > 0 ? arr : undefined;
18
+ }
19
+ function parseJsonArray(raw, name) {
20
+ if (!raw)
21
+ return undefined;
22
+ const trimmed = raw.trim();
23
+ // If the value looks like a JSON array (`[...]`), require it to BE valid JSON.
24
+ // Otherwise fall back to CSV parsing — that way `a,b,c` works too, but a
25
+ // malformed `[bogus]` doesn't silently become a single-element string array.
26
+ if (trimmed.startsWith('[')) {
27
+ try {
28
+ const parsed = JSON.parse(trimmed);
29
+ if (!Array.isArray(parsed) || !parsed.every((x) => typeof x === 'string')) {
30
+ throw new Error('not a JSON array of strings');
31
+ }
32
+ return parsed.length > 0 ? parsed : undefined;
33
+ }
34
+ catch (err) {
35
+ throw new Error(`${name}: malformed JSON array (${err instanceof Error ? err.message : String(err)})`);
36
+ }
37
+ }
38
+ return parseCsv(trimmed);
39
+ }
40
+ function parseBool(raw) {
41
+ if (raw === undefined)
42
+ return undefined;
43
+ const lc = raw.trim().toLowerCase();
44
+ if (lc === 'true' || lc === '1' || lc === 'yes')
45
+ return true;
46
+ if (lc === 'false' || lc === '0' || lc === 'no')
47
+ return false;
48
+ return undefined;
49
+ }
50
+ function parseSort(raw) {
51
+ if (!raw)
52
+ return undefined;
53
+ const lc = raw.trim().toLowerCase();
54
+ return lc === 'price' || lc === 'throughput' || lc === 'latency' ? lc : undefined;
55
+ }
56
+ function parseDataCollection(raw) {
57
+ if (!raw)
58
+ return undefined;
59
+ const lc = raw.trim().toLowerCase();
60
+ return lc === 'allow' || lc === 'deny' ? lc : undefined;
61
+ }
62
+ /**
63
+ * Read provider routing defaults from `OPENROUTER_PROVIDER_*` env vars.
64
+ * Invalid values are silently dropped (never throw at server start).
65
+ */
66
+ export function readProviderDefaults() {
67
+ const env = process.env;
68
+ const out = {};
69
+ const quantizations = parseCsv(env.OPENROUTER_PROVIDER_QUANTIZATIONS);
70
+ if (quantizations)
71
+ out.quantizations = quantizations;
72
+ const ignore = parseCsv(env.OPENROUTER_PROVIDER_IGNORE);
73
+ if (ignore)
74
+ out.ignore = ignore;
75
+ const sort = parseSort(env.OPENROUTER_PROVIDER_SORT);
76
+ if (sort)
77
+ out.sort = sort;
78
+ try {
79
+ const order = parseJsonArray(env.OPENROUTER_PROVIDER_ORDER, 'OPENROUTER_PROVIDER_ORDER');
80
+ if (order)
81
+ out.order = order;
82
+ }
83
+ catch {
84
+ /* silently drop malformed env var */
85
+ }
86
+ const requireParams = parseBool(env.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS);
87
+ if (requireParams !== undefined)
88
+ out.require_parameters = requireParams;
89
+ const dc = parseDataCollection(env.OPENROUTER_PROVIDER_DATA_COLLECTION);
90
+ if (dc)
91
+ out.data_collection = dc;
92
+ const af = parseBool(env.OPENROUTER_PROVIDER_ALLOW_FALLBACKS);
93
+ if (af !== undefined)
94
+ out.allow_fallbacks = af;
95
+ return out;
96
+ }
97
+ /**
98
+ * Merge caller overrides on top of env defaults. Explicit `undefined`
99
+ * values in the override drop back to the default (they don't erase it);
100
+ * to actually erase a field, pass `null`.
101
+ */
102
+ export function mergeProviderOptions(defaults, overrides) {
103
+ if (!overrides)
104
+ return { ...defaults };
105
+ const out = { ...defaults };
106
+ for (const [key, value] of Object.entries(overrides)) {
107
+ if (value === undefined)
108
+ continue;
109
+ out[key] = value;
110
+ }
111
+ return out;
112
+ }
113
+ /**
114
+ * Build the OpenRouter `provider` request-body field from options.
115
+ * Returns `undefined` when nothing is set so we don't send `{}`.
116
+ */
117
+ export function buildProviderBody(opts) {
118
+ const entries = Object.entries(opts).filter(([, v]) => {
119
+ if (v === undefined || v === null)
120
+ return false;
121
+ if (Array.isArray(v) && v.length === 0)
122
+ return false;
123
+ return true;
124
+ });
125
+ if (entries.length === 0)
126
+ return undefined;
127
+ return Object.fromEntries(entries);
128
+ }
129
+ /**
130
+ * Read the default `max_tokens` from `OPENROUTER_MAX_TOKENS` env var.
131
+ * Invalid or non-positive values are ignored.
132
+ */
133
+ export function readDefaultMaxTokens() {
134
+ const raw = process.env.OPENROUTER_MAX_TOKENS;
135
+ if (!raw)
136
+ return undefined;
137
+ const n = parseInt(raw, 10);
138
+ return Number.isFinite(n) && n > 0 ? n : undefined;
139
+ }
140
+ /**
141
+ * Resolve the effective `max_tokens` for a request. Request value wins
142
+ * over env default.
143
+ */
144
+ export function resolveMaxTokens(requested) {
145
+ if (typeof requested === 'number' && requested > 0)
146
+ return requested;
147
+ return readDefaultMaxTokens();
148
+ }
@@ -34,7 +34,7 @@ export class ToolHandlers {
34
34
  tools: [
35
35
  {
36
36
  name: 'chat_completion',
37
- description: 'Send messages to an OpenRouter model and get a response',
37
+ description: 'Send messages to an OpenRouter model and get a response. Supports provider routing (quantizations / ignore / sort / order / require_parameters / data_collection / allow_fallbacks) and model variant suffixes (`:nitro` for faster, `:floor` for cheapest).',
38
38
  annotations: {
39
39
  readOnlyHint: false,
40
40
  destructiveHint: false,
@@ -43,7 +43,10 @@ export class ToolHandlers {
43
43
  inputSchema: {
44
44
  type: 'object',
45
45
  properties: {
46
- model: { type: 'string', description: 'Model ID (optional, uses default)' },
46
+ model: {
47
+ type: 'string',
48
+ description: 'Model ID (optional, uses default). Append `:nitro` for faster/experimental variants or `:floor` for the cheapest available variant (e.g. `openai/gpt-4o:nitro`).',
49
+ },
47
50
  messages: {
48
51
  type: 'array',
49
52
  minItems: 1,
@@ -59,7 +62,50 @@ export class ToolHandlers {
59
62
  },
60
63
  },
61
64
  temperature: { type: 'number', minimum: 0, maximum: 2 },
62
- max_tokens: { type: 'number', minimum: 1 },
65
+ max_tokens: {
66
+ type: 'number',
67
+ minimum: 1,
68
+ description: 'Max completion tokens. Falls back to `OPENROUTER_MAX_TOKENS` env var if unset.',
69
+ },
70
+ provider: {
71
+ type: 'object',
72
+ description: 'OpenRouter provider-routing overrides. Merges on top of `OPENROUTER_PROVIDER_*` env defaults. See https://openrouter.ai/docs/features/provider-routing',
73
+ properties: {
74
+ quantizations: {
75
+ type: 'array',
76
+ items: { type: 'string' },
77
+ description: 'Filter providers by quantization (e.g. `["fp16","int8"]`).',
78
+ },
79
+ ignore: {
80
+ type: 'array',
81
+ items: { type: 'string' },
82
+ description: 'Exclude these provider slugs (e.g. `["openai","anthropic"]`).',
83
+ },
84
+ sort: {
85
+ type: 'string',
86
+ enum: ['price', 'throughput', 'latency'],
87
+ description: 'Sort providers by this criterion.',
88
+ },
89
+ order: {
90
+ type: 'array',
91
+ items: { type: 'string' },
92
+ description: 'Prioritized list of provider IDs (e.g. `["openai/gpt-4o","anthropic/claude-3-opus"]`).',
93
+ },
94
+ require_parameters: {
95
+ type: 'boolean',
96
+ description: 'Only use providers that support every parameter in the request.',
97
+ },
98
+ data_collection: {
99
+ type: 'string',
100
+ enum: ['allow', 'deny'],
101
+ description: 'Whether providers may collect request data.',
102
+ },
103
+ allow_fallbacks: {
104
+ type: 'boolean',
105
+ description: 'Allow fallback to unlisted providers when preferred ones fail.',
106
+ },
107
+ },
108
+ },
63
109
  },
64
110
  required: ['messages'],
65
111
  },
@@ -185,7 +231,10 @@ export class ToolHandlers {
185
231
  },
186
232
  {
187
233
  name: 'generate_image',
188
- description: 'Generate an image from a text prompt',
234
+ description: 'Generate an image from a text prompt. Optionally conditioned on one or more ' +
235
+ 'reference images (file paths, http(s) URLs, or data URLs) for character / style ' +
236
+ 'consistency. Sends `modalities: ["image","text"]` by default; override via the ' +
237
+ '`modalities` field if needed.',
189
238
  annotations: {
190
239
  readOnlyHint: false,
191
240
  destructiveHint: false,
@@ -230,6 +279,21 @@ export class ToolHandlers {
230
279
  type: 'string',
231
280
  description: 'Optional path to save the image. Routed through the OPENROUTER_OUTPUT_DIR sandbox.',
232
281
  },
282
+ input_images: {
283
+ type: 'array',
284
+ items: { type: 'string' },
285
+ description: 'Optional reference images for visual consistency. Each entry may be a ' +
286
+ 'local file path (sandboxed to OPENROUTER_INPUT_DIR / OPENROUTER_OUTPUT_DIR / ' +
287
+ 'cwd), an http(s) URL, or a `data:image/...;base64,...` URL. Inlined as ' +
288
+ 'multimodal user content in the order given.',
289
+ },
290
+ modalities: {
291
+ type: 'array',
292
+ items: { type: 'string' },
293
+ description: 'Override the default `modalities: ["image","text"]` sent to OpenRouter. ' +
294
+ 'Most callers should leave this unset. Provide e.g. ["text"] to suppress ' +
295
+ 'image output for inspection / captioning.',
296
+ },
233
297
  },
234
298
  required: ['prompt'],
235
299
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stabgan/openrouter-mcp-multimodal",
3
- "version": "3.1.1",
3
+ "version": "4.0.0",
4
4
  "mcpName": "io.github.stabgan/openrouter-multimodal",
5
5
  "description": "MCP server for OpenRouter with text chat, image analysis + generation, audio analysis + generation, video analysis, and video generation (Veo 3.1 / Sora 2 Pro / Seedance / Wan)",
6
6
  "type": "module",
@@ -42,7 +42,7 @@
42
42
  "url": "https://github.com/stabgan/openrouter-mcp-multimodal/issues"
43
43
  },
44
44
  "homepage": "https://github.com/stabgan/openrouter-mcp-multimodal#readme",
45
- "license": "MIT",
45
+ "license": "Apache-2.0",
46
46
  "engines": {
47
47
  "node": ">=18.0.0"
48
48
  },