@teampitch/mcpx 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +179 -0
- package/README.md +33 -0
- package/mcpx.example.json +43 -0
- package/package.json +52 -0
- package/src/ast.test.ts +41 -0
- package/src/ast.ts +42 -0
- package/src/auth.test.ts +150 -0
- package/src/auth.ts +144 -0
- package/src/backends.test.ts +205 -0
- package/src/backends.ts +159 -0
- package/src/config.test.ts +149 -0
- package/src/config.ts +134 -0
- package/src/executor.test.ts +155 -0
- package/src/executor.ts +195 -0
- package/src/index.ts +364 -0
- package/src/init.ts +115 -0
- package/src/k8s-controller.test.ts +108 -0
- package/src/k8s-controller.ts +201 -0
- package/src/oauth.test.ts +232 -0
- package/src/oauth.ts +265 -0
- package/src/openapi.test.ts +223 -0
- package/src/openapi.ts +253 -0
- package/src/stdio.ts +176 -0
- package/src/watcher.ts +100 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
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 made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other
|
|
42
|
+
transformations represent, as a whole, an original work of authorship.
|
|
43
|
+
For the purposes of this License, Derivative Works shall not include
|
|
44
|
+
works that remain separable from, or merely link (or bind by name)
|
|
45
|
+
to the interfaces of, the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of tracking and
|
|
55
|
+
implementing Contributions, but excluding communication that is
|
|
56
|
+
conspicuously marked or designated in writing by the copyright owner
|
|
57
|
+
as "Not a Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and included
|
|
61
|
+
within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent claims licensable
|
|
76
|
+
by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by the combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or any Contribution
|
|
81
|
+
embodied within the Work constitutes direct or contributory patent
|
|
82
|
+
infringement, then any patent licenses granted to You under this License
|
|
83
|
+
for that Work shall terminate as of the date such litigation is filed.
|
|
84
|
+
|
|
85
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
86
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
87
|
+
modifications, and in Source or Object form, provided that You
|
|
88
|
+
meet the following conditions:
|
|
89
|
+
|
|
90
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
91
|
+
Works a copy of this License; and
|
|
92
|
+
|
|
93
|
+
(b) You must cause any modified files to carry prominent notices
|
|
94
|
+
stating that You changed the files; and
|
|
95
|
+
|
|
96
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
97
|
+
that You distribute, all copyright, patent, trademark, and
|
|
98
|
+
attribution notices from the Source form of the Work,
|
|
99
|
+
excluding those notices that do not pertain to any part of
|
|
100
|
+
the Derivative Works; and
|
|
101
|
+
|
|
102
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
103
|
+
distribution, You must include a readable copy of the
|
|
104
|
+
attribution notices contained within such NOTICE file, in
|
|
105
|
+
at least one of the following places: within a NOTICE text
|
|
106
|
+
file distributed as part of the Derivative Works; within
|
|
107
|
+
the Source form or documentation, if provided along with the
|
|
108
|
+
Derivative Works; or, within a display generated by the
|
|
109
|
+
Derivative Works, if and wherever such third-party notices
|
|
110
|
+
normally appear. The contents of the NOTICE file are for
|
|
111
|
+
informational purposes only and do not modify the License.
|
|
112
|
+
You may add Your own attribution notices within Derivative
|
|
113
|
+
Works that You distribute, alongside or in addition to the
|
|
114
|
+
NOTICE text from the Work, provided that such additional
|
|
115
|
+
attribution notices cannot be construed as modifying the License.
|
|
116
|
+
|
|
117
|
+
You may add Your own license statement for Your modifications and
|
|
118
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
119
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
120
|
+
Contribution, either on an original basis or as a derivative of
|
|
121
|
+
the original Contribution.
|
|
122
|
+
|
|
123
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
124
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
125
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
126
|
+
this License, without any additional terms or conditions.
|
|
127
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
128
|
+
the terms of any separate license agreement you may have executed
|
|
129
|
+
with Licensor regarding such Contributions.
|
|
130
|
+
|
|
131
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
132
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
133
|
+
except as required for reasonable and customary use in describing the
|
|
134
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
135
|
+
|
|
136
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
137
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
138
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
139
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
140
|
+
implied, including, without limitation, any warranties or conditions
|
|
141
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
142
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
143
|
+
appropriateness of using or reproducing the Work and assume any
|
|
144
|
+
risks associated with Your exercise of permissions under this License.
|
|
145
|
+
|
|
146
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
147
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
148
|
+
unless required by applicable law (such as deliberate and grossly
|
|
149
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
150
|
+
liable to You for damages, including any direct, indirect, special,
|
|
151
|
+
incidental, or exemplary damages of any character arising as a
|
|
152
|
+
result of this License or out of the use or inability to use the
|
|
153
|
+
Work (even if such Contributor has been advised of the possibility
|
|
154
|
+
of such damages).
|
|
155
|
+
|
|
156
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
157
|
+
the Work or Derivative Works thereof, You may elect to offer,
|
|
158
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
159
|
+
or other liability obligations and/or rights consistent with this
|
|
160
|
+
License. However, in accepting such obligations, You may offer only
|
|
161
|
+
conditions that are fully consistent with this License and for which
|
|
162
|
+
you can accept complete indemnity from damages arising as a result
|
|
163
|
+
of Warranty or other liability.
|
|
164
|
+
|
|
165
|
+
END OF TERMS AND CONDITIONS
|
|
166
|
+
|
|
167
|
+
Copyright 2024 mcpx contributors
|
|
168
|
+
|
|
169
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
170
|
+
you may not use this file except in compliance with the License.
|
|
171
|
+
You may obtain a copy of the License at
|
|
172
|
+
|
|
173
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
174
|
+
|
|
175
|
+
Unless required by applicable law or agreed to in writing, software
|
|
176
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
177
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
178
|
+
See the License for the specific language governing permissions and
|
|
179
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# mcpx
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
Collapse multiple MCP servers into **2 tools**: `search` and `execute`.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
Without mcpx: agent ← 120 tool schemas (~84,000 tokens)
|
|
9
|
+
With mcpx: agent ← 2 tools (~1,000 tokens)
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Quick start
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
bunx mcpx-tools init # create mcpx.json
|
|
16
|
+
claude mcp add mcpx -- bunx mcpx-tools stdio mcpx.json # connect agent
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Docs
|
|
20
|
+
|
|
21
|
+
- [Configuration](docs/configuration.md) — `mcpx.json` format, env vars, backends
|
|
22
|
+
- [Agent setup](docs/agents.md) — Claude Code, Cursor, Codex, Amp, OpenCode
|
|
23
|
+
- [Team deployment](docs/deployment.md) — Docker, Helm, standalone HTTP
|
|
24
|
+
- [Security](docs/security.md) — V8 sandbox, permissions, credential isolation
|
|
25
|
+
- [Examples](docs/examples.md) — Grafana, GitHub, multi-backend configs
|
|
26
|
+
|
|
27
|
+
## How it works
|
|
28
|
+
|
|
29
|
+
Your agent calls `search` to find tools, then `execute` to run JavaScript that calls them. Code runs in a sandboxed V8 isolate — no filesystem, no network, no env access. Tool calls are the only way out.
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
|
|
33
|
+
Apache-2.0
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"port": 3100,
|
|
3
|
+
"authToken": "${MCPX_AUTH_TOKEN}",
|
|
4
|
+
"backends": {
|
|
5
|
+
"grafana": {
|
|
6
|
+
"transport": "stdio",
|
|
7
|
+
"command": "uvx",
|
|
8
|
+
"args": ["mcp-grafana"],
|
|
9
|
+
"env": {
|
|
10
|
+
"GRAFANA_URL": "${GRAFANA_URL}",
|
|
11
|
+
"GRAFANA_SERVICE_ACCOUNT_TOKEN": "${GRAFANA_TOKEN}"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"plane": {
|
|
15
|
+
"transport": "stdio",
|
|
16
|
+
"command": "uvx",
|
|
17
|
+
"args": ["plane-mcp-server", "stdio"],
|
|
18
|
+
"env": {
|
|
19
|
+
"PLANE_API_KEY": "${PLANE_API_KEY}",
|
|
20
|
+
"PLANE_WORKSPACE_SLUG": "${PLANE_WORKSPACE_SLUG}",
|
|
21
|
+
"PLANE_BASE_URL": "${PLANE_BASE_URL}"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"github": {
|
|
25
|
+
"transport": "stdio",
|
|
26
|
+
"command": "docker",
|
|
27
|
+
"args": [
|
|
28
|
+
"run",
|
|
29
|
+
"-i",
|
|
30
|
+
"--rm",
|
|
31
|
+
"-e",
|
|
32
|
+
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
|
33
|
+
"-e",
|
|
34
|
+
"GITHUB_TOOLSETS",
|
|
35
|
+
"ghcr.io/github/github-mcp-server"
|
|
36
|
+
],
|
|
37
|
+
"env": {
|
|
38
|
+
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}",
|
|
39
|
+
"GITHUB_TOOLSETS": "context,repos,issues,pull_requests"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@teampitch/mcpx",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Self-hosted MCP Code Mode gateway — aggregate multiple MCP servers behind 2 tools with V8 isolate execution",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"claude",
|
|
7
|
+
"code-mode",
|
|
8
|
+
"gateway",
|
|
9
|
+
"grafana",
|
|
10
|
+
"mcp"
|
|
11
|
+
],
|
|
12
|
+
"license": "Apache-2.0",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "https://github.com/arek-e/mcpx"
|
|
16
|
+
},
|
|
17
|
+
"bin": {
|
|
18
|
+
"mcpx": "./src/index.ts"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"src/",
|
|
22
|
+
"mcpx.example.json",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "src/index.ts",
|
|
27
|
+
"scripts": {
|
|
28
|
+
"dev": "bun run --watch src/index.ts",
|
|
29
|
+
"build": "bun build src/index.ts --target=bun --minify --outfile=dist/server.js",
|
|
30
|
+
"start": "bun dist/server.js",
|
|
31
|
+
"test": "bun test",
|
|
32
|
+
"lint": "oxlint src/",
|
|
33
|
+
"format": "biome format --write src/",
|
|
34
|
+
"format:check": "biome format src/",
|
|
35
|
+
"check": "bun run lint && bun run format:check",
|
|
36
|
+
"precommit": "bun run check && bun test",
|
|
37
|
+
"prepublishOnly": "bun run check && bun test"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@modelcontextprotocol/sdk": "^1.12.1",
|
|
41
|
+
"acorn": "^8.16.0",
|
|
42
|
+
"hono": "^4.7.10",
|
|
43
|
+
"jose": "^6.2.2",
|
|
44
|
+
"neverthrow": "^8.2.0",
|
|
45
|
+
"secure-exec": "^0.2.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@biomejs/biome": "^2.4.10",
|
|
49
|
+
"@types/bun": "^1.2.14",
|
|
50
|
+
"oxlint": "^1.58.0"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/ast.test.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { describe, test, expect } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { validateSyntax } from "./ast.js";
|
|
4
|
+
|
|
5
|
+
describe("validateSyntax", () => {
|
|
6
|
+
test("returns null for valid code", () => {
|
|
7
|
+
expect(validateSyntax("const x = 1; export default x;")).toBeNull();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test("returns null for async/await code", () => {
|
|
11
|
+
expect(validateSyntax("const x = await Promise.resolve(1); export default x;")).toBeNull();
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test("returns error for missing closing brace", () => {
|
|
15
|
+
const result = validateSyntax("function foo() {");
|
|
16
|
+
expect(result).not.toBeNull();
|
|
17
|
+
expect(result!.line).toBeGreaterThan(0);
|
|
18
|
+
expect(result!.message).toBeTruthy();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("returns error for unterminated string", () => {
|
|
22
|
+
const result = validateSyntax('const x = "hello');
|
|
23
|
+
expect(result).not.toBeNull();
|
|
24
|
+
expect(result!.message).toBeTruthy();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("includes snippet in error", () => {
|
|
28
|
+
const result = validateSyntax("const x = 1;\nconst y = {\nconst z = 3;");
|
|
29
|
+
expect(result).not.toBeNull();
|
|
30
|
+
expect(result!.snippet).toBeTruthy();
|
|
31
|
+
expect(result!.snippet).toContain("|");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("handles arrow functions", () => {
|
|
35
|
+
expect(validateSyntax("const fn = (x) => x + 1; export default fn;")).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("handles template literals", () => {
|
|
39
|
+
expect(validateSyntax("const x = `hello ${1 + 2}`; export default x;")).toBeNull();
|
|
40
|
+
});
|
|
41
|
+
});
|
package/src/ast.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import * as acorn from "acorn";
|
|
2
|
+
|
|
3
|
+
export interface AstError {
|
|
4
|
+
message: string;
|
|
5
|
+
line: number;
|
|
6
|
+
column: number;
|
|
7
|
+
snippet?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Validate JavaScript syntax before V8 execution for better error messages */
|
|
11
|
+
export function validateSyntax(code: string): AstError | null {
|
|
12
|
+
try {
|
|
13
|
+
acorn.parse(code, { sourceType: "module", ecmaVersion: "latest" });
|
|
14
|
+
return null;
|
|
15
|
+
} catch (e) {
|
|
16
|
+
const err = e as acorn.SyntaxError & {
|
|
17
|
+
loc?: { line: number; column: number };
|
|
18
|
+
};
|
|
19
|
+
const line = err.loc?.line ?? 0;
|
|
20
|
+
const column = err.loc?.column ?? 0;
|
|
21
|
+
|
|
22
|
+
// Build a 3-line snippet around the error
|
|
23
|
+
const lines = code.split("\n");
|
|
24
|
+
const start = Math.max(0, line - 2);
|
|
25
|
+
const end = Math.min(lines.length, line + 1);
|
|
26
|
+
const snippet = lines
|
|
27
|
+
.slice(start, end)
|
|
28
|
+
.map((l, i) => {
|
|
29
|
+
const lineNum = start + i + 1;
|
|
30
|
+
const marker = lineNum === line ? ">" : " ";
|
|
31
|
+
return `${marker} ${lineNum} | ${l}`;
|
|
32
|
+
})
|
|
33
|
+
.join("\n");
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
message: err.message.replace(/\(\d+:\d+\)$/, "").trim(),
|
|
37
|
+
line,
|
|
38
|
+
column,
|
|
39
|
+
snippet,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/auth.test.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { describe, test, expect } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { SignJWT } from "jose";
|
|
4
|
+
|
|
5
|
+
import { createAuthVerifier, filterBackendsByClaims, type AuthClaims } from "./auth.js";
|
|
6
|
+
import type { Backend } from "./backends.js";
|
|
7
|
+
import type { McpxConfig, BackendConfig } from "./config.js";
|
|
8
|
+
|
|
9
|
+
function makeConfig(overrides: Partial<McpxConfig> = {}): McpxConfig {
|
|
10
|
+
return { port: 3100, backends: {}, ...overrides };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function makeMockBackend(name: string): [string, Backend] {
|
|
14
|
+
return [name, { name, client: {} as Backend["client"], tools: [] }];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe("createAuthVerifier", () => {
|
|
18
|
+
test("returns null when no auth configured", () => {
|
|
19
|
+
const verifier = createAuthVerifier(makeConfig());
|
|
20
|
+
expect(verifier).toBeNull();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("validates simple bearer token (legacy authToken)", async () => {
|
|
24
|
+
const verifier = createAuthVerifier(makeConfig({ authToken: "secret" }));
|
|
25
|
+
expect(verifier).not.toBeNull();
|
|
26
|
+
|
|
27
|
+
const ok = await verifier!("secret");
|
|
28
|
+
expect(ok.isOk()).toBe(true);
|
|
29
|
+
|
|
30
|
+
const fail = await verifier!("wrong");
|
|
31
|
+
expect(fail.isErr()).toBe(true);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("validates simple bearer token (auth.bearer)", async () => {
|
|
35
|
+
const verifier = createAuthVerifier(makeConfig({ auth: { bearer: "my-token" } }));
|
|
36
|
+
expect(verifier).not.toBeNull();
|
|
37
|
+
|
|
38
|
+
const ok = await verifier!("my-token");
|
|
39
|
+
expect(ok.isOk()).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("validates JWT with HMAC secret", async () => {
|
|
43
|
+
const secret = "test-secret-at-least-32-chars-long!!";
|
|
44
|
+
const verifier = createAuthVerifier(makeConfig({ auth: { jwt: { secret } } }));
|
|
45
|
+
expect(verifier).not.toBeNull();
|
|
46
|
+
|
|
47
|
+
const token = await new SignJWT({
|
|
48
|
+
sub: "user-1",
|
|
49
|
+
email: "test@example.com",
|
|
50
|
+
roles: ["admin"],
|
|
51
|
+
})
|
|
52
|
+
.setProtectedHeader({ alg: "HS256" })
|
|
53
|
+
.setExpirationTime("1h")
|
|
54
|
+
.sign(new TextEncoder().encode(secret));
|
|
55
|
+
|
|
56
|
+
const result = await verifier!(token);
|
|
57
|
+
expect(result.isOk()).toBe(true);
|
|
58
|
+
if (result.isOk()) {
|
|
59
|
+
expect(result.value.sub).toBe("user-1");
|
|
60
|
+
expect(result.value.email).toBe("test@example.com");
|
|
61
|
+
expect(result.value.roles).toEqual(["admin"]);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("rejects expired JWT", async () => {
|
|
66
|
+
const secret = "test-secret-at-least-32-chars-long!!";
|
|
67
|
+
const verifier = createAuthVerifier(makeConfig({ auth: { jwt: { secret } } }));
|
|
68
|
+
|
|
69
|
+
const token = await new SignJWT({ sub: "user-1" })
|
|
70
|
+
.setProtectedHeader({ alg: "HS256" })
|
|
71
|
+
.setExpirationTime("-1h") // already expired
|
|
72
|
+
.sign(new TextEncoder().encode(secret));
|
|
73
|
+
|
|
74
|
+
const result = await verifier!(token);
|
|
75
|
+
expect(result.isErr()).toBe(true);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("rejects JWT with wrong secret", async () => {
|
|
79
|
+
const verifier = createAuthVerifier(
|
|
80
|
+
makeConfig({
|
|
81
|
+
auth: { jwt: { secret: "correct-secret-at-least-32-chars!!" } },
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const token = await new SignJWT({ sub: "user-1" })
|
|
86
|
+
.setProtectedHeader({ alg: "HS256" })
|
|
87
|
+
.setExpirationTime("1h")
|
|
88
|
+
.sign(new TextEncoder().encode("wrong-secret-at-least-32-chars!!!"));
|
|
89
|
+
|
|
90
|
+
const result = await verifier!(token);
|
|
91
|
+
expect(result.isErr()).toBe(true);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe("filterBackendsByClaims", () => {
|
|
96
|
+
const backends = new Map<string, Backend>([
|
|
97
|
+
makeMockBackend("grafana"),
|
|
98
|
+
makeMockBackend("github"),
|
|
99
|
+
makeMockBackend("public"),
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
const configs: Record<string, BackendConfig> = {
|
|
103
|
+
grafana: {
|
|
104
|
+
transport: "stdio",
|
|
105
|
+
command: "grafana-mcp",
|
|
106
|
+
allowedRoles: ["admin", "devops"],
|
|
107
|
+
},
|
|
108
|
+
github: {
|
|
109
|
+
transport: "stdio",
|
|
110
|
+
command: "github-mcp",
|
|
111
|
+
allowedTeams: ["platform"],
|
|
112
|
+
},
|
|
113
|
+
public: { transport: "stdio", command: "public-mcp" },
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
test("returns all backends when no restrictions", () => {
|
|
117
|
+
const noRestrictions: Record<string, BackendConfig> = {
|
|
118
|
+
grafana: { transport: "stdio", command: "grafana-mcp" },
|
|
119
|
+
github: { transport: "stdio", command: "github-mcp" },
|
|
120
|
+
public: { transport: "stdio", command: "public-mcp" },
|
|
121
|
+
};
|
|
122
|
+
const claims: AuthClaims = { sub: "user" };
|
|
123
|
+
const filtered = filterBackendsByClaims(backends, claims, noRestrictions);
|
|
124
|
+
expect(filtered.size).toBe(3);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("filters by role", () => {
|
|
128
|
+
const claims: AuthClaims = { roles: ["admin"] };
|
|
129
|
+
const filtered = filterBackendsByClaims(backends, claims, configs);
|
|
130
|
+
expect(filtered.has("grafana")).toBe(true);
|
|
131
|
+
expect(filtered.has("github")).toBe(false); // needs team, not role
|
|
132
|
+
expect(filtered.has("public")).toBe(true); // no restrictions
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("filters by team", () => {
|
|
136
|
+
const claims: AuthClaims = { teams: ["platform"] };
|
|
137
|
+
const filtered = filterBackendsByClaims(backends, claims, configs);
|
|
138
|
+
expect(filtered.has("grafana")).toBe(false); // needs role
|
|
139
|
+
expect(filtered.has("github")).toBe(true);
|
|
140
|
+
expect(filtered.has("public")).toBe(true);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("excludes when no matching claims", () => {
|
|
144
|
+
const claims: AuthClaims = { roles: ["viewer"], teams: ["marketing"] };
|
|
145
|
+
const filtered = filterBackendsByClaims(backends, claims, configs);
|
|
146
|
+
expect(filtered.has("grafana")).toBe(false);
|
|
147
|
+
expect(filtered.has("github")).toBe(false);
|
|
148
|
+
expect(filtered.has("public")).toBe(true);
|
|
149
|
+
});
|
|
150
|
+
});
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { jwtVerify, createRemoteJWKSet, type JWTPayload } from "jose";
|
|
2
|
+
import { ok, err, type Result } from "neverthrow";
|
|
3
|
+
|
|
4
|
+
import type { Backend } from "./backends.js";
|
|
5
|
+
import type { McpxConfig, BackendConfig } from "./config.js";
|
|
6
|
+
|
|
7
|
+
export interface AuthClaims {
|
|
8
|
+
sub?: string;
|
|
9
|
+
email?: string;
|
|
10
|
+
roles?: string[];
|
|
11
|
+
teams?: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type VerifyFn = (token: string) => Promise<Result<AuthClaims, string>>;
|
|
15
|
+
|
|
16
|
+
function extractClaims(payload: JWTPayload): AuthClaims {
|
|
17
|
+
return {
|
|
18
|
+
sub: payload.sub,
|
|
19
|
+
email: payload.email as string | undefined,
|
|
20
|
+
roles: (payload.roles ?? payload.role) as string[] | undefined,
|
|
21
|
+
teams: (payload.teams ?? payload.team) as string[] | undefined,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Create a token verification function based on config */
|
|
26
|
+
export function createAuthVerifier(config: McpxConfig): VerifyFn | null {
|
|
27
|
+
const auth = config.auth;
|
|
28
|
+
const legacyToken = config.authToken;
|
|
29
|
+
|
|
30
|
+
// No auth configured
|
|
31
|
+
if (!auth && !legacyToken) return null;
|
|
32
|
+
|
|
33
|
+
// Build a list of verification strategies (tried in order)
|
|
34
|
+
const strategies: VerifyFn[] = [];
|
|
35
|
+
|
|
36
|
+
// Simple bearer token (legacy authToken or auth.bearer)
|
|
37
|
+
const bearerToken = auth?.bearer ?? legacyToken;
|
|
38
|
+
if (bearerToken) {
|
|
39
|
+
strategies.push(async (token: string) => {
|
|
40
|
+
if (token !== bearerToken) return err("invalid token");
|
|
41
|
+
return ok({});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// JWT with JWKS
|
|
46
|
+
if (auth?.jwt?.jwksUrl) {
|
|
47
|
+
const jwks = createRemoteJWKSet(new URL(auth.jwt.jwksUrl));
|
|
48
|
+
const opts: { audience?: string; issuer?: string } = {};
|
|
49
|
+
if (auth.jwt.audience) opts.audience = auth.jwt.audience;
|
|
50
|
+
if (auth.jwt.issuer) opts.issuer = auth.jwt.issuer;
|
|
51
|
+
strategies.push(async (token: string) => {
|
|
52
|
+
try {
|
|
53
|
+
const { payload } = await jwtVerify(token, jwks, opts);
|
|
54
|
+
return ok(extractClaims(payload));
|
|
55
|
+
} catch (e) {
|
|
56
|
+
return err((e as Error).message);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// JWT with HMAC secret
|
|
62
|
+
if (auth?.jwt?.secret) {
|
|
63
|
+
const secret = new TextEncoder().encode(auth.jwt.secret);
|
|
64
|
+
const opts: { audience?: string; issuer?: string } = {};
|
|
65
|
+
if (auth.jwt.audience) opts.audience = auth.jwt.audience;
|
|
66
|
+
if (auth.jwt.issuer) opts.issuer = auth.jwt.issuer;
|
|
67
|
+
strategies.push(async (token: string) => {
|
|
68
|
+
try {
|
|
69
|
+
const { payload } = await jwtVerify(token, secret, opts);
|
|
70
|
+
return ok(extractClaims(payload));
|
|
71
|
+
} catch (e) {
|
|
72
|
+
return err((e as Error).message);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// OAuth-issued tokens (signed with OAuth tokenSecret)
|
|
78
|
+
if (auth?.oauth?.tokenSecret) {
|
|
79
|
+
const oauthSecret = new TextEncoder().encode(auth.oauth.tokenSecret);
|
|
80
|
+
strategies.push(async (token: string) => {
|
|
81
|
+
try {
|
|
82
|
+
const { payload } = await jwtVerify(token, oauthSecret, {
|
|
83
|
+
issuer: auth.oauth!.issuer,
|
|
84
|
+
});
|
|
85
|
+
return ok(extractClaims(payload));
|
|
86
|
+
} catch (e) {
|
|
87
|
+
return err((e as Error).message);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (strategies.length === 0) return null;
|
|
93
|
+
|
|
94
|
+
// Try each strategy; return first success, or last error
|
|
95
|
+
return async (token: string) => {
|
|
96
|
+
let lastError = "invalid token";
|
|
97
|
+
for (const strategy of strategies) {
|
|
98
|
+
const result = await strategy(token);
|
|
99
|
+
if (result.isOk()) return result;
|
|
100
|
+
lastError = result.error;
|
|
101
|
+
}
|
|
102
|
+
return err(lastError);
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Filter backends by JWT claims (roles/teams) */
|
|
107
|
+
export function filterBackendsByClaims(
|
|
108
|
+
backends: Map<string, Backend>,
|
|
109
|
+
claims: AuthClaims,
|
|
110
|
+
configs: Record<string, BackendConfig>,
|
|
111
|
+
): Map<string, Backend> {
|
|
112
|
+
const filtered = new Map<string, Backend>();
|
|
113
|
+
|
|
114
|
+
for (const [name, backend] of backends) {
|
|
115
|
+
const config = configs[name];
|
|
116
|
+
if (!config) continue;
|
|
117
|
+
|
|
118
|
+
// No restrictions — allow access
|
|
119
|
+
if (!config.allowedRoles?.length && !config.allowedTeams?.length) {
|
|
120
|
+
filtered.set(name, backend);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Check role intersection
|
|
125
|
+
if (config.allowedRoles?.length) {
|
|
126
|
+
const hasRole = claims.roles?.some((r) => config.allowedRoles!.includes(r));
|
|
127
|
+
if (hasRole) {
|
|
128
|
+
filtered.set(name, backend);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Check team intersection
|
|
134
|
+
if (config.allowedTeams?.length) {
|
|
135
|
+
const hasTeam = claims.teams?.some((t) => config.allowedTeams!.includes(t));
|
|
136
|
+
if (hasTeam) {
|
|
137
|
+
filtered.set(name, backend);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return filtered;
|
|
144
|
+
}
|