@commoditypriceapi/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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CommodityPriceAPI
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,106 @@
1
+ # CommodityPriceAPI MCP Server
2
+
3
+ Official MCP server for [CommodityPriceAPI](https://commoditypriceapi.com). Exposes 8 MCP tools for real-time and historical commodity rates — gold, silver, oil, and 130+ other commodities — to any MCP-compatible client (Claude Desktop, Cursor, Windsurf, VS Code, Cline, etc).
4
+
5
+ | Item | Value |
6
+ | --------- | ------------------------ |
7
+ | Package | `@commoditypriceapi/mcp` |
8
+ | Transport | `stdio` |
9
+ | Node.js | `>=18` |
10
+
11
+ ## Quick Start
12
+
13
+ 1. [Get a free CommodityPriceAPI key](https://commoditypriceapi.com/auth/signup)
14
+ 2. Add this to your MCP client config:
15
+
16
+ ```json
17
+ {
18
+ "mcpServers": {
19
+ "commoditypriceapi": {
20
+ "command": "npx",
21
+ "args": ["-y", "@commoditypriceapi/mcp"],
22
+ "env": {
23
+ "COMMODITYPRICEAPI_KEY": "<YOUR_API_KEY>"
24
+ }
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ 3. Restart your client.
31
+ 4. Test it: ask **"What's the current gold price?"**
32
+
33
+ ## Install by Client
34
+
35
+ ### Claude Desktop
36
+
37
+ Add the block above to `claude_desktop_config.json`, then restart Claude Desktop.
38
+
39
+ ### Cursor / Windsurf / Cline / VS Code
40
+
41
+ Add the same `commoditypriceapi` block to that client's MCP server config file and restart the client.
42
+
43
+ ### Any other MCP client
44
+
45
+ ```json
46
+ {
47
+ "command": "npx",
48
+ "args": ["-y", "@commoditypriceapi/mcp"],
49
+ "env": {
50
+ "COMMODITYPRICEAPI_KEY": "<YOUR_API_KEY>"
51
+ }
52
+ }
53
+ ```
54
+
55
+ ## Tools
56
+
57
+ | Tool | Endpoint | What it does |
58
+ | ---------------------- | ---------------------------- | ----------------------------------------------------------------|
59
+ | `get_usage` | `GET /v2/usage` | Current plan, quota, and usage |
60
+ | `list_symbols` | `GET /v2/symbols` | All supported commodity symbols with category/currency/unit |
61
+ | `get_latest_rates` | `GET /v2/rates/latest` | Latest rates for one or more symbols |
62
+ | `get_gold_price` | `GET /v2/rates/latest/xau` | Shortcut for the latest gold rate |
63
+ | `get_silver_price` | `GET /v2/rates/latest/xag` | Shortcut for the latest silver rate |
64
+ | `get_historical_rates` | `GET /v2/rates/historical` | OHLC rates for one or more symbols on a specific past date |
65
+ | `get_time_series` | `GET /v2/rates/time-series` | Daily rates between two dates (max 1 year span) |
66
+ | `get_fluctuation` | `GET /v2/rates/fluctuation` | Start/end rate, change, and % change over a date range |
67
+
68
+ All tools that take `symbols` accept a comma-separated list (e.g. `XAU,XAG,BRENTOIL`). Use `list_symbols` to look up valid symbols.
69
+
70
+ ## Authentication
71
+
72
+ The server sends your API key to CommodityPriceAPI via **both** the `x-api-key` header and the `apiKey` query parameter — the upstream API accepts either, so this covers all cases without extra config.
73
+
74
+ | Variable | Required | Description |
75
+ | ------------------------ | -------- | ---------------------------------- |
76
+ | `COMMODITYPRICEAPI_KEY` | Yes | Your CommodityPriceAPI key |
77
+ | `COMMODITYPRICEAPI_REQUEST_TIMEOUT_MS` | No | Upstream request timeout in ms (default `15000`) |
78
+
79
+ ## Error Handling
80
+
81
+ Tool calls never crash the server. Upstream errors (invalid symbol, missing date, quota exceeded, etc.) are returned as structured tool results with `error`, `code`, `message`, and a `guidance` field so the client can explain what went wrong instead of just echoing a status code.
82
+
83
+ ## Building from Source
84
+
85
+ ```bash
86
+ git clone https://github.com/commoditypriceapi/commoditypriceapi-mcp.git
87
+ cd commoditypriceapi-mcp
88
+ npm install
89
+ npm run build
90
+ ```
91
+
92
+ Run it directly:
93
+
94
+ ```bash
95
+ COMMODITYPRICEAPI_KEY=<YOUR_KEY> node dist/cli.js
96
+ ```
97
+
98
+ Inspect with the MCP Inspector:
99
+
100
+ ```bash
101
+ COMMODITYPRICEAPI_KEY=<YOUR_KEY> npx @modelcontextprotocol/inspector node dist/cli.js
102
+ ```
103
+
104
+ ## License
105
+
106
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { createServer } from "./server.js";
4
+ async function main() {
5
+ const server = createServer();
6
+ const transport = new StdioServerTransport();
7
+ await server.connect(transport);
8
+ // Log to stderr only — stdout is reserved for the MCP protocol stream.
9
+ console.error("commoditypriceapi-mcp server running on stdio");
10
+ }
11
+ main().catch((err) => {
12
+ console.error("Fatal error starting commoditypriceapi-mcp server:", err);
13
+ process.exit(1);
14
+ });
package/dist/client.js ADDED
@@ -0,0 +1,70 @@
1
+ const BASE_URL = "https://api.commoditypriceapi.com/v2";
2
+ export class CommodityApiError extends Error {
3
+ code;
4
+ errorType;
5
+ path;
6
+ constructor(code, errorType, message, path) {
7
+ super(message);
8
+ this.name = "CommodityApiError";
9
+ this.code = code;
10
+ this.errorType = errorType;
11
+ this.path = path;
12
+ }
13
+ }
14
+ function getApiKey() {
15
+ const key = process.env.COMMODITYPRICEAPI_KEY;
16
+ if (!key) {
17
+ throw new Error("COMMODITYPRICEAPI_KEY is not set. Add it to your MCP client config's env block.");
18
+ }
19
+ return key;
20
+ }
21
+ /**
22
+ * Calls a CommodityPriceAPI v2 endpoint.
23
+ * Sends the API key via both the x-api-key header AND the apiKey query
24
+ * param, since the upstream API accepts either.
25
+ */
26
+ export async function callCommodityApi(path, params = {}) {
27
+ const apiKey = getApiKey();
28
+ const url = new URL(BASE_URL + path);
29
+ url.searchParams.set("apiKey", apiKey);
30
+ for (const [key, value] of Object.entries(params)) {
31
+ if (value !== undefined && value !== "") {
32
+ url.searchParams.set(key, value);
33
+ }
34
+ }
35
+ const timeoutMs = Number(process.env.COMMODITYPRICEAPI_REQUEST_TIMEOUT_MS ?? 15000);
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
38
+ let response;
39
+ try {
40
+ response = await fetch(url.toString(), {
41
+ method: "GET",
42
+ headers: {
43
+ "x-api-key": apiKey,
44
+ accept: "application/json",
45
+ },
46
+ signal: controller.signal,
47
+ });
48
+ }
49
+ catch (err) {
50
+ if (err instanceof Error && err.name === "AbortError") {
51
+ throw new CommodityApiError(499, "REQUEST_TIMEOUT", `Request to CommodityPriceAPI timed out after ${timeoutMs}ms.`);
52
+ }
53
+ throw new CommodityApiError(502, "UPSTREAM_UNREACHABLE", `Could not reach CommodityPriceAPI: ${err.message}`);
54
+ }
55
+ finally {
56
+ clearTimeout(timer);
57
+ }
58
+ const text = await response.text();
59
+ let body;
60
+ try {
61
+ body = text ? JSON.parse(text) : {};
62
+ }
63
+ catch {
64
+ throw new CommodityApiError(response.status, "INVALID_RESPONSE", `CommodityPriceAPI returned a non-JSON response: ${text.slice(0, 500)}`);
65
+ }
66
+ if (!response.ok) {
67
+ throw new CommodityApiError(response.status, body.error ?? "UNKNOWN_ERROR", body.message ?? `CommodityPriceAPI request failed with status ${response.status}.`, body.path);
68
+ }
69
+ return body;
70
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createServer } from "./server.js";
package/dist/server.js ADDED
@@ -0,0 +1,209 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { callCommodityApi, CommodityApiError } from "./client.js";
4
+ const symbolsParam = z
5
+ .string()
6
+ .describe("Comma-separated commodity symbols, e.g. 'XAU,XAG,BRENTOIL'. See the list_symbols tool for valid values.");
7
+ const dateParam = z.string().describe("Date in YYYY-MM-DD format.");
8
+ function textResult(data) {
9
+ return {
10
+ content: [
11
+ {
12
+ type: "text",
13
+ text: JSON.stringify(data, null, 2),
14
+ },
15
+ ],
16
+ };
17
+ }
18
+ function errorResult(err) {
19
+ if (err instanceof CommodityApiError) {
20
+ return {
21
+ isError: true,
22
+ content: [
23
+ {
24
+ type: "text",
25
+ text: JSON.stringify({
26
+ error: err.errorType,
27
+ code: err.code,
28
+ message: err.message,
29
+ guidance: guidanceFor(err.code, err.errorType),
30
+ }, null, 2),
31
+ },
32
+ ],
33
+ };
34
+ }
35
+ return {
36
+ isError: true,
37
+ content: [
38
+ {
39
+ type: "text",
40
+ text: JSON.stringify({ error: "UNEXPECTED_ERROR", message: err.message }, null, 2),
41
+ },
42
+ ],
43
+ };
44
+ }
45
+ function guidanceFor(code, errorType) {
46
+ switch (code) {
47
+ case 401:
48
+ return "Check that COMMODITYPRICEAPI_KEY is set correctly in your MCP client config.";
49
+ case 402:
50
+ return "Your trial or subscription doesn't cover this request. Check your plan on the CommodityPriceAPI dashboard.";
51
+ case 403:
52
+ return "You've hit your API key's usage limit. Upgrade your plan or wait for the quota to reset.";
53
+ case 404:
54
+ if (errorType === "SYMBOL_NOT_FOUND") {
55
+ return "Call list_symbols to see valid commodity symbols.";
56
+ }
57
+ return "The requested resource was not found.";
58
+ case 429:
59
+ return "You're being rate limited. Wait a minute and try again.";
60
+ default:
61
+ return "CommodityPriceAPI returned an error outside the documented cases; treat the message above as authoritative.";
62
+ }
63
+ }
64
+ export function createServer() {
65
+ const server = new McpServer({
66
+ name: "commoditypriceapi-mcp",
67
+ version: "1.0.0",
68
+ });
69
+ server.registerTool("get_usage", {
70
+ title: "Get API usage",
71
+ description: "Returns the current plan, quota, and usage for the configured CommodityPriceAPI key.",
72
+ inputSchema: {},
73
+ }, async () => {
74
+ try {
75
+ const data = await callCommodityApi("/usage");
76
+ return textResult(data);
77
+ }
78
+ catch (err) {
79
+ return errorResult(err);
80
+ }
81
+ });
82
+ server.registerTool("list_symbols", {
83
+ title: "List supported commodity symbols",
84
+ description: "Returns all commodity symbols supported by CommodityPriceAPI, including category, default currency, and unit. Use this to look up a symbol before calling rate tools.",
85
+ inputSchema: {},
86
+ }, async () => {
87
+ try {
88
+ const data = await callCommodityApi("/symbols");
89
+ return textResult(data);
90
+ }
91
+ catch (err) {
92
+ return errorResult(err);
93
+ }
94
+ });
95
+ server.registerTool("get_latest_rates", {
96
+ title: "Get latest commodity rates",
97
+ description: "Returns the latest rates for one or more commodity symbols (e.g. gold, silver, crude oil). Rates may lag up to 10 minutes depending on plan. Use 'quote' to convert to a specific currency (Premium/Plus plans only).",
98
+ inputSchema: {
99
+ symbols: symbolsParam,
100
+ quote: z
101
+ .string()
102
+ .optional()
103
+ .describe("Target quote currency code (e.g. 'USD', 'EUR'). Premium/Plus plans only; omit to use each symbol's default currency."),
104
+ },
105
+ }, async ({ symbols, quote }) => {
106
+ try {
107
+ const data = await callCommodityApi("/rates/latest", { symbols, quote });
108
+ return textResult(data);
109
+ }
110
+ catch (err) {
111
+ return errorResult(err);
112
+ }
113
+ });
114
+ server.registerTool("get_gold_price", {
115
+ title: "Get latest gold (XAU) price",
116
+ description: "Shortcut for the latest gold (XAU) rate without needing to pass a symbols list.",
117
+ inputSchema: {
118
+ quote: z
119
+ .string()
120
+ .optional()
121
+ .describe("Target quote currency code. Premium/Plus plans only."),
122
+ },
123
+ }, async ({ quote }) => {
124
+ try {
125
+ const data = await callCommodityApi("/rates/latest/xau", { quote });
126
+ return textResult(data);
127
+ }
128
+ catch (err) {
129
+ return errorResult(err);
130
+ }
131
+ });
132
+ server.registerTool("get_silver_price", {
133
+ title: "Get latest silver (XAG) price",
134
+ description: "Shortcut for the latest silver (XAG) rate without needing to pass a symbols list.",
135
+ inputSchema: {
136
+ quote: z
137
+ .string()
138
+ .optional()
139
+ .describe("Target quote currency code. Premium/Plus plans only."),
140
+ },
141
+ }, async ({ quote }) => {
142
+ try {
143
+ const data = await callCommodityApi("/rates/latest/xag", { quote });
144
+ return textResult(data);
145
+ }
146
+ catch (err) {
147
+ return errorResult(err);
148
+ }
149
+ });
150
+ server.registerTool("get_historical_rates", {
151
+ title: "Get historical commodity rates",
152
+ description: "Returns open/high/low/close rates for one or more symbols on a specific past date (available back to 1990-01-01). If no rate exists for that exact date, the API returns the nearest available date.",
153
+ inputSchema: {
154
+ symbols: symbolsParam,
155
+ date: dateParam,
156
+ },
157
+ }, async ({ symbols, date }) => {
158
+ try {
159
+ const data = await callCommodityApi("/rates/historical", { symbols, date });
160
+ return textResult(data);
161
+ }
162
+ catch (err) {
163
+ return errorResult(err);
164
+ }
165
+ });
166
+ server.registerTool("get_time_series", {
167
+ title: "Get commodity time series",
168
+ description: "Returns daily historical rates for one or more symbols between two dates. The date range cannot exceed 1 year.",
169
+ inputSchema: {
170
+ symbols: symbolsParam,
171
+ startDate: dateParam,
172
+ endDate: dateParam,
173
+ },
174
+ }, async ({ symbols, startDate, endDate }) => {
175
+ try {
176
+ const data = await callCommodityApi("/rates/time-series", {
177
+ symbols,
178
+ startDate,
179
+ endDate,
180
+ });
181
+ return textResult(data);
182
+ }
183
+ catch (err) {
184
+ return errorResult(err);
185
+ }
186
+ });
187
+ server.registerTool("get_fluctuation", {
188
+ title: "Get commodity price fluctuation",
189
+ description: "Returns how one or more commodity symbols changed between a start and end date: start rate, end rate, absolute change, and percent change.",
190
+ inputSchema: {
191
+ symbols: symbolsParam,
192
+ startDate: dateParam,
193
+ endDate: dateParam,
194
+ },
195
+ }, async ({ symbols, startDate, endDate }) => {
196
+ try {
197
+ const data = await callCommodityApi("/rates/fluctuation", {
198
+ symbols,
199
+ startDate,
200
+ endDate,
201
+ });
202
+ return textResult(data);
203
+ }
204
+ catch (err) {
205
+ return errorResult(err);
206
+ }
207
+ });
208
+ return server;
209
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@commoditypriceapi/mcp",
3
+ "version": "1.0.0",
4
+ "description": "Official MCP server for CommodityPriceAPI \u2014 real-time and historical commodity rates (gold, silver, oil, and 130+ more) as MCP tools for Claude, Cursor, Windsurf, and any MCP client.",
5
+ "keywords": [
6
+ "mcp",
7
+ "model-context-protocol",
8
+ "commodity-prices",
9
+ "gold-price",
10
+ "silver-price",
11
+ "commoditypriceapi",
12
+ "claude",
13
+ "ai-tools"
14
+ ],
15
+ "homepage": "https://commoditypriceapi.com",
16
+ "bugs": "https://github.com/commoditypriceapi/commoditypriceapi-mcp/issues",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/commoditypriceapi/commoditypriceapi-mcp.git"
20
+ },
21
+ "license": "MIT",
22
+ "author": "CommodityPriceAPI",
23
+ "type": "module",
24
+ "bin": {
25
+ "commoditypriceapi-mcp": "dist/cli.js"
26
+ },
27
+ "main": "dist/index.js",
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.json && chmod +x dist/cli.js",
38
+ "prepublishOnly": "npm run build",
39
+ "dev": "tsc -p tsconfig.json --watch",
40
+ "start": "node dist/cli.js"
41
+ },
42
+ "dependencies": {
43
+ "@modelcontextprotocol/sdk": "^1.12.0",
44
+ "zod": "^3.24.1"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.10.5",
48
+ "typescript": "^5.7.3"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }