@avalkit/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erik Bustos
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,95 @@
1
+ # @avalkit/mcp
2
+
3
+ [Avalkit](https://avalkit.com) MCP server — adds spend governance and tamper-evident audit logging to your AI assistant.
4
+
5
+ ## What it does
6
+
7
+ Avalkit gives AI agents and AI-using teams:
8
+ - **Pre-flight spend approval** — every payment, charge, or budget consumption checked against your rules before it happens
9
+ - **Per-user budgets** — different limits for different teams, customers, or agent identities
10
+ - **Tamper-evident audit log** — hash-chained record of every approval and denial, suitable for compliance reviews
11
+ - **Stripe integration** — execute approved intents as real charges with one call
12
+
13
+ This MCP server exposes Avalkit's API as five tools: `avalkit_create_intent`, `avalkit_execute_intent`, `avalkit_list_audit`, `avalkit_list_rules`, `avalkit_upsert_rules`.
14
+
15
+ ## Install
16
+
17
+ ### Claude Desktop
18
+
19
+ Add this to `~/Library/Application Support/Claude/claude_desktop_config.json`:
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "avalkit": {
25
+ "command": "npx",
26
+ "args": ["@avalkit/mcp"]
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ Restart Claude Desktop. The first time you use an Avalkit tool, your browser will open to authorize the connection. Click Allow once and you're done.
33
+
34
+ ### Cursor
35
+
36
+ Add to your Cursor MCP settings:
37
+
38
+ ```json
39
+ {
40
+ "avalkit": {
41
+ "command": "npx",
42
+ "args": ["@avalkit/mcp"]
43
+ }
44
+ }
45
+ ```
46
+
47
+ ### Other MCP clients
48
+
49
+ Same pattern — `npx @avalkit/mcp` is the command, no arguments needed.
50
+
51
+ ## Authentication
52
+
53
+ Two modes:
54
+
55
+ ### OAuth (default)
56
+
57
+ When you first use an Avalkit tool, the MCP server opens your browser to `mcp.avalkit.com/oauth/authorize`. You sign in with your email (magic link), click Allow, and tokens are saved to `~/.avalkit/tokens.json`. Tokens auto-refresh.
58
+
59
+ To re-authenticate: `npx @avalkit/mcp login`
60
+ To disconnect: `npx @avalkit/mcp logout`
61
+
62
+ ### API key (for SDK or scripted use)
63
+
64
+ Set `AVALKIT_API_KEY` as an environment variable:
65
+
66
+ ```json
67
+ {
68
+ "mcpServers": {
69
+ "avalkit": {
70
+ "command": "npx",
71
+ "args": ["@avalkit/mcp"],
72
+ "env": {
73
+ "AVALKIT_API_KEY": "ak_test_..."
74
+ }
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ Get an API key at [app.avalkit.com](https://app.avalkit.com).
81
+
82
+ ## Pricing
83
+
84
+ Free during beta. Up to 10,000 intents per month per account. Email founders@avalkit.com if you need more.
85
+
86
+ ## License
87
+
88
+ MIT — see LICENSE.
89
+
90
+ ## Links
91
+
92
+ - [Avalkit dashboard](https://app.avalkit.com)
93
+ - [Documentation](https://avalkit.com)
94
+ - [GitHub](https://github.com/avalkit/avalkit)
95
+ - [Contact](mailto:founders@avalkit.com)
package/dist/index.js ADDED
@@ -0,0 +1,306 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Avalkit MCP Server
4
+ *
5
+ * Exposes Avalkit's spend governance API as MCP tools, so any MCP-compatible
6
+ * AI assistant (Claude Desktop, Claude Code, Cursor, etc.) can natively use
7
+ * Avalkit for spend governance and audit.
8
+ */
9
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
12
+ import { z } from "zod";
13
+ import { getValidAccessToken, runOAuthFlow, clearTokens } from "./oauth.js";
14
+ // --- Configuration ---
15
+ const AVALKIT_API_KEY = process.env.AVALKIT_API_KEY;
16
+ const AVALKIT_BASE_URL = process.env.AVALKIT_BASE_URL || "https://mcp.avalkit.com";
17
+ // Auth mode: if AVALKIT_API_KEY is set, use it directly (legacy/dev path).
18
+ // Otherwise, use OAuth — token is fetched/refreshed on demand.
19
+ const USE_OAUTH = !AVALKIT_API_KEY;
20
+ // --- CLI mode: handle "login" / "logout" subcommands ---
21
+ const cliCommand = process.argv[2];
22
+ if (cliCommand === "login") {
23
+ console.error("Starting Avalkit OAuth login...");
24
+ runOAuthFlow()
25
+ .then((tokens) => {
26
+ console.error("✓ Login successful!");
27
+ console.error(` Access token expires: ${new Date(tokens.access_token_expires_at * 1000).toLocaleString()}`);
28
+ console.error(` Tokens saved to ~/.avalkit/tokens.json`);
29
+ process.exit(0);
30
+ })
31
+ .catch((err) => {
32
+ console.error("✗ Login failed:", err.message);
33
+ process.exit(1);
34
+ });
35
+ }
36
+ else if (cliCommand === "logout") {
37
+ clearTokens();
38
+ console.error("✓ Logged out. Tokens cleared.");
39
+ process.exit(0);
40
+ }
41
+ // --- Helpers ---
42
+ async function getAuthHeader() {
43
+ if (USE_OAUTH) {
44
+ const accessToken = await getValidAccessToken();
45
+ return `Bearer ${accessToken}`;
46
+ }
47
+ return `Bearer ${AVALKIT_API_KEY}`;
48
+ }
49
+ async function avalkitRequest(method, path, body, isRetry = false) {
50
+ const url = `${AVALKIT_BASE_URL}${path}`;
51
+ const authHeader = await getAuthHeader();
52
+ const response = await fetch(url, {
53
+ method,
54
+ headers: {
55
+ Authorization: authHeader,
56
+ "Content-Type": "application/json",
57
+ "User-Agent": "avalkit-mcp/0.1.0",
58
+ },
59
+ body: body ? JSON.stringify(body) : undefined,
60
+ });
61
+ // OAuth-specific: if we get a 401 and we're using OAuth, our token might be stale.
62
+ // Clear tokens and retry once (which will trigger refresh or re-auth).
63
+ if (response.status === 401 && USE_OAUTH && !isRetry) {
64
+ clearTokens();
65
+ return avalkitRequest(method, path, body, true);
66
+ }
67
+ if (!response.ok) {
68
+ const text = await response.text();
69
+ throw new Error(`Avalkit API error (${response.status}): ${text || response.statusText}`);
70
+ }
71
+ if (response.status === 204) {
72
+ return { success: true };
73
+ }
74
+ return await response.json();
75
+ }
76
+ // --- Input schemas (zod) ---
77
+ const CreateIntentSchema = z.object({
78
+ amount: z
79
+ .number()
80
+ .int()
81
+ .positive()
82
+ .describe("Amount in minor units (e.g. cents for USD). 4700 = $47.00"),
83
+ currency: z
84
+ .string()
85
+ .length(3)
86
+ .describe("ISO 4217 currency code, lowercase. Example: 'usd'"),
87
+ purpose: z
88
+ .string()
89
+ .min(10)
90
+ .describe("Human-readable description of the spend. Will be shown in audit logs."),
91
+ category: z
92
+ .string()
93
+ .describe("Category like 'travel', 'food', 'ai_inference', 'refunds', 'software'"),
94
+ user_id: z
95
+ .string()
96
+ .describe("Your end-user identifier — the principal on whose behalf to spend"),
97
+ });
98
+ const ExecuteIntentSchema = z.object({
99
+ intent_id: z.string().describe("The intent ID returned from create_intent"),
100
+ payment_method: z
101
+ .string()
102
+ .describe("Stripe payment method ID. Use 'pm_card_visa' for testing."),
103
+ idempotency_key: z
104
+ .string()
105
+ .min(8)
106
+ .describe("Unique key for safe retries. Often the intent_id with a suffix."),
107
+ });
108
+ const ListAuditSchema = z.object({
109
+ user_id: z.string().optional().describe("Filter by user_id"),
110
+ status: z
111
+ .enum(["approved", "denied", "succeeded", "failed"])
112
+ .optional()
113
+ .describe("Filter by status"),
114
+ category: z.string().optional().describe("Filter by category"),
115
+ limit: z
116
+ .number()
117
+ .int()
118
+ .min(1)
119
+ .max(100)
120
+ .optional()
121
+ .describe("Max results, 1-100. Default 25."),
122
+ });
123
+ const UpsertRulesSchema = z.object({
124
+ user_id: z.string().describe("The end-user identifier these rules apply to"),
125
+ max_amount_per_intent: z
126
+ .number()
127
+ .int()
128
+ .positive()
129
+ .optional()
130
+ .describe("Maximum amount per single intent in minor units"),
131
+ daily_limit: z
132
+ .number()
133
+ .int()
134
+ .positive()
135
+ .optional()
136
+ .describe("Maximum total spend per 24 hours in minor units"),
137
+ allowed_categories: z
138
+ .array(z.string())
139
+ .optional()
140
+ .describe("If set, only intents in these categories are allowed. Example: ['ai_inference', 'refunds']"),
141
+ });
142
+ // --- MCP Server ---
143
+ const server = new Server({
144
+ name: "avalkit",
145
+ version: "0.1.0",
146
+ }, {
147
+ capabilities: {
148
+ tools: {},
149
+ },
150
+ });
151
+ // --- Tool registration ---
152
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
153
+ return {
154
+ tools: [
155
+ {
156
+ name: "avalkit_create_intent",
157
+ description: "Submit a spend intent for approval. Avalkit checks the intent against the configured rules for the user and returns approved or denied with a reason. Use this BEFORE any payment, refund, or other spend action to ensure it's within policy.",
158
+ inputSchema: {
159
+ type: "object",
160
+ properties: {
161
+ amount: { type: "integer", description: "Amount in minor units" },
162
+ currency: { type: "string", description: "ISO 4217 code" },
163
+ purpose: { type: "string", description: "Human-readable reason" },
164
+ category: { type: "string", description: "Spend category" },
165
+ user_id: { type: "string", description: "End-user identifier" },
166
+ },
167
+ required: ["amount", "currency", "purpose", "category", "user_id"],
168
+ },
169
+ },
170
+ {
171
+ name: "avalkit_execute_intent",
172
+ description: "Execute a previously approved intent by charging via Stripe. Only call this if create_intent returned status='approved'. Returns a receipt with the Stripe charge ID and audit hash.",
173
+ inputSchema: {
174
+ type: "object",
175
+ properties: {
176
+ intent_id: {
177
+ type: "string",
178
+ description: "Intent ID from create_intent",
179
+ },
180
+ payment_method: {
181
+ type: "string",
182
+ description: "Stripe payment method ID",
183
+ },
184
+ idempotency_key: {
185
+ type: "string",
186
+ description: "Unique retry key",
187
+ },
188
+ },
189
+ required: ["intent_id", "payment_method", "idempotency_key"],
190
+ },
191
+ },
192
+ {
193
+ name: "avalkit_list_audit",
194
+ description: "List entries from the tamper-evident audit log. Each entry is hash-chained to the previous, providing cryptographic proof of integrity. Useful for compliance reviews and answering 'what did the agent do?'",
195
+ inputSchema: {
196
+ type: "object",
197
+ properties: {
198
+ user_id: { type: "string" },
199
+ status: {
200
+ type: "string",
201
+ enum: ["approved", "denied", "succeeded", "failed"],
202
+ },
203
+ category: { type: "string" },
204
+ limit: { type: "integer", minimum: 1, maximum: 100 },
205
+ },
206
+ },
207
+ },
208
+ {
209
+ name: "avalkit_list_rules",
210
+ description: "List all spend rules currently configured for this account. Each rule defines per-user limits like max_amount_per_intent, daily_limit, and allowed_categories.",
211
+ inputSchema: {
212
+ type: "object",
213
+ properties: {},
214
+ },
215
+ },
216
+ {
217
+ name: "avalkit_upsert_rules",
218
+ description: "Create or update spend rules for a specific user_id. Use this to set per-user budgets. The most restrictive rule wins when an intent is evaluated.",
219
+ inputSchema: {
220
+ type: "object",
221
+ properties: {
222
+ user_id: { type: "string" },
223
+ max_amount_per_intent: { type: "integer", minimum: 1 },
224
+ daily_limit: { type: "integer", minimum: 1 },
225
+ allowed_categories: {
226
+ type: "array",
227
+ items: { type: "string" },
228
+ },
229
+ },
230
+ required: ["user_id"],
231
+ },
232
+ },
233
+ ],
234
+ };
235
+ });
236
+ // --- Tool execution ---
237
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
238
+ const { name, arguments: args } = request.params;
239
+ try {
240
+ switch (name) {
241
+ case "avalkit_create_intent": {
242
+ const input = CreateIntentSchema.parse(args);
243
+ const result = await avalkitRequest("POST", "/v1/intents", input);
244
+ return {
245
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
246
+ };
247
+ }
248
+ case "avalkit_execute_intent": {
249
+ const input = ExecuteIntentSchema.parse(args);
250
+ const { intent_id, ...body } = input;
251
+ const result = await avalkitRequest("POST", `/v1/intents/${intent_id}/execute`, body);
252
+ return {
253
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
254
+ };
255
+ }
256
+ case "avalkit_list_audit": {
257
+ const input = ListAuditSchema.parse(args);
258
+ const params = new URLSearchParams();
259
+ for (const [key, value] of Object.entries(input)) {
260
+ if (value !== undefined) {
261
+ params.append(key, String(value));
262
+ }
263
+ }
264
+ const qs = params.toString();
265
+ const path = qs ? `/v1/audit?${qs}` : "/v1/audit";
266
+ const result = await avalkitRequest("GET", path);
267
+ return {
268
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
269
+ };
270
+ }
271
+ case "avalkit_list_rules": {
272
+ const result = await avalkitRequest("GET", "/v1/rules");
273
+ return {
274
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
275
+ };
276
+ }
277
+ case "avalkit_upsert_rules": {
278
+ const input = UpsertRulesSchema.parse(args);
279
+ const { user_id, ...body } = input;
280
+ const result = await avalkitRequest("PUT", `/v1/rules/${user_id}`, body);
281
+ return {
282
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
283
+ };
284
+ }
285
+ default:
286
+ throw new Error(`Unknown tool: ${name}`);
287
+ }
288
+ }
289
+ catch (error) {
290
+ const message = error instanceof Error ? error.message : String(error);
291
+ return {
292
+ content: [{ type: "text", text: `Error: ${message}` }],
293
+ isError: true,
294
+ };
295
+ }
296
+ });
297
+ // --- Start the server ---
298
+ async function main() {
299
+ const transport = new StdioServerTransport();
300
+ await server.connect(transport);
301
+ console.error("Avalkit MCP server running on stdio");
302
+ }
303
+ main().catch((error) => {
304
+ console.error("Fatal error:", error);
305
+ process.exit(1);
306
+ });
package/dist/oauth.js ADDED
@@ -0,0 +1,227 @@
1
+ /**
2
+ * OAuth 2.0 client logic for the Avalkit MCP server.
3
+ *
4
+ * Handles the full PKCE flow: opens browser, runs local callback server,
5
+ * exchanges code for tokens, refreshes when needed, persists to disk.
6
+ */
7
+ import { createHash, randomBytes } from "crypto";
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "fs";
9
+ import { createServer } from "http";
10
+ import { homedir } from "os";
11
+ import { dirname, join } from "path";
12
+ import open from "open";
13
+ const OAUTH_BASE_URL = "https://mcp.avalkit.com";
14
+ const CLIENT_ID = "claude_desktop";
15
+ const REDIRECT_PORT = 33418;
16
+ const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;
17
+ const TOKENS_PATH = join(homedir(), ".avalkit", "tokens.json");
18
+ // --- Token storage ---
19
+ export function loadTokens() {
20
+ if (!existsSync(TOKENS_PATH))
21
+ return null;
22
+ try {
23
+ const data = readFileSync(TOKENS_PATH, "utf-8");
24
+ return JSON.parse(data);
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ export function saveTokens(tokens) {
31
+ const dir = dirname(TOKENS_PATH);
32
+ if (!existsSync(dir)) {
33
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
34
+ }
35
+ writeFileSync(TOKENS_PATH, JSON.stringify(tokens, null, 2));
36
+ chmodSync(TOKENS_PATH, 0o600); // Owner read/write only
37
+ }
38
+ export function clearTokens() {
39
+ if (existsSync(TOKENS_PATH)) {
40
+ writeFileSync(TOKENS_PATH, "");
41
+ }
42
+ }
43
+ // --- PKCE helpers ---
44
+ function base64UrlEncode(buf) {
45
+ return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
46
+ }
47
+ function generatePkcePair() {
48
+ const verifier = base64UrlEncode(randomBytes(48));
49
+ const challenge = base64UrlEncode(createHash("sha256").update(verifier).digest());
50
+ return { verifier, challenge };
51
+ }
52
+ // --- OAuth flow ---
53
+ /**
54
+ * Run the full OAuth flow:
55
+ * 1. Generate PKCE pair
56
+ * 2. Open browser to authorize URL
57
+ * 3. Spin up local server to catch callback
58
+ * 4. Exchange code for tokens
59
+ * 5. Save tokens to disk
60
+ */
61
+ export async function runOAuthFlow() {
62
+ const { verifier, challenge } = generatePkcePair();
63
+ const state = base64UrlEncode(randomBytes(16));
64
+ const authUrl = new URL(`${OAUTH_BASE_URL}/oauth/authorize`);
65
+ authUrl.searchParams.set("response_type", "code");
66
+ authUrl.searchParams.set("client_id", CLIENT_ID);
67
+ authUrl.searchParams.set("redirect_uri", REDIRECT_URI);
68
+ authUrl.searchParams.set("code_challenge", challenge);
69
+ authUrl.searchParams.set("code_challenge_method", "S256");
70
+ authUrl.searchParams.set("state", state);
71
+ authUrl.searchParams.set("scope", "read write");
72
+ // Promise that resolves with the authorization code
73
+ const codePromise = new Promise((resolve, reject) => {
74
+ const server = createServer((req, res) => {
75
+ if (!req.url) {
76
+ res.writeHead(400);
77
+ res.end("Bad request");
78
+ return;
79
+ }
80
+ const url = new URL(req.url, `http://localhost:${REDIRECT_PORT}`);
81
+ if (url.pathname !== "/callback") {
82
+ res.writeHead(404);
83
+ res.end("Not found");
84
+ return;
85
+ }
86
+ const error = url.searchParams.get("error");
87
+ if (error) {
88
+ res.writeHead(400, { "Content-Type": "text/html" });
89
+ res.end(`<html><body><h2>Authorization denied</h2><p>${error}</p><p>You can close this window.</p></body></html>`);
90
+ server.close();
91
+ reject(new Error(`OAuth error: ${error}`));
92
+ return;
93
+ }
94
+ const returnedState = url.searchParams.get("state");
95
+ const code = url.searchParams.get("code");
96
+ if (returnedState !== state) {
97
+ res.writeHead(400);
98
+ res.end("State mismatch — possible CSRF attempt");
99
+ server.close();
100
+ reject(new Error("State mismatch"));
101
+ return;
102
+ }
103
+ if (!code) {
104
+ res.writeHead(400);
105
+ res.end("No code returned");
106
+ server.close();
107
+ reject(new Error("No code returned"));
108
+ return;
109
+ }
110
+ // Success page
111
+ res.writeHead(200, { "Content-Type": "text/html" });
112
+ res.end(`
113
+ <html><head><title>Avalkit connected</title></head>
114
+ <body style="font-family: -apple-system, sans-serif; max-width: 480px; margin: 64px auto; padding: 24px; text-align: center;">
115
+ <h2>Avalkit connected</h2>
116
+ <p>You can close this tab and return to your AI assistant.</p>
117
+ </body></html>
118
+ `);
119
+ server.close();
120
+ resolve(code);
121
+ });
122
+ server.on("error", (err) => {
123
+ reject(err);
124
+ });
125
+ server.listen(REDIRECT_PORT, "127.0.0.1", () => {
126
+ // Open the browser once the local server is listening
127
+ open(authUrl.toString()).catch(() => {
128
+ console.error(`Open this URL in your browser:\n${authUrl.toString()}`);
129
+ });
130
+ });
131
+ });
132
+ const code = await codePromise;
133
+ // Exchange the code for tokens
134
+ const tokens = await exchangeCodeForTokens(code, verifier);
135
+ saveTokens(tokens);
136
+ return tokens;
137
+ }
138
+ /**
139
+ * Exchange an authorization code (with PKCE verifier) for tokens.
140
+ */
141
+ async function exchangeCodeForTokens(code, verifier) {
142
+ const body = new URLSearchParams({
143
+ grant_type: "authorization_code",
144
+ code,
145
+ redirect_uri: REDIRECT_URI,
146
+ client_id: CLIENT_ID,
147
+ code_verifier: verifier,
148
+ });
149
+ const response = await fetch(`${OAUTH_BASE_URL}/oauth/token`, {
150
+ method: "POST",
151
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
152
+ body: body.toString(),
153
+ });
154
+ if (!response.ok) {
155
+ const text = await response.text();
156
+ throw new Error(`Token exchange failed (${response.status}): ${text}`);
157
+ }
158
+ const data = await response.json();
159
+ const now = Math.floor(Date.now() / 1000);
160
+ return {
161
+ access_token: data.access_token,
162
+ refresh_token: data.refresh_token,
163
+ access_token_expires_at: now + data.expires_in,
164
+ refresh_token_expires_at: now + 365 * 24 * 60 * 60, // 1 year, matches server
165
+ scope: data.scope || "",
166
+ };
167
+ }
168
+ /**
169
+ * Refresh an expired access token using the refresh token.
170
+ */
171
+ export async function refreshAccessToken(refreshToken) {
172
+ const body = new URLSearchParams({
173
+ grant_type: "refresh_token",
174
+ refresh_token: refreshToken,
175
+ client_id: CLIENT_ID,
176
+ });
177
+ const response = await fetch(`${OAUTH_BASE_URL}/oauth/token`, {
178
+ method: "POST",
179
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
180
+ body: body.toString(),
181
+ });
182
+ if (!response.ok) {
183
+ const text = await response.text();
184
+ throw new Error(`Token refresh failed (${response.status}): ${text}`);
185
+ }
186
+ const data = await response.json();
187
+ const now = Math.floor(Date.now() / 1000);
188
+ const tokens = {
189
+ access_token: data.access_token,
190
+ refresh_token: data.refresh_token,
191
+ access_token_expires_at: now + data.expires_in,
192
+ refresh_token_expires_at: now + 365 * 24 * 60 * 60,
193
+ scope: data.scope || "",
194
+ };
195
+ saveTokens(tokens);
196
+ return tokens;
197
+ }
198
+ /**
199
+ * Get a valid access token, refreshing if necessary.
200
+ * Triggers full OAuth flow if no tokens exist.
201
+ */
202
+ export async function getValidAccessToken() {
203
+ let tokens = loadTokens();
204
+ // No tokens stored — run the full flow
205
+ if (!tokens) {
206
+ tokens = await runOAuthFlow();
207
+ return tokens.access_token;
208
+ }
209
+ const now = Math.floor(Date.now() / 1000);
210
+ // Access token still valid (with 60s buffer)
211
+ if (tokens.access_token_expires_at > now + 60) {
212
+ return tokens.access_token;
213
+ }
214
+ // Access token expired but refresh token might still work
215
+ if (tokens.refresh_token_expires_at > now) {
216
+ try {
217
+ tokens = await refreshAccessToken(tokens.refresh_token);
218
+ return tokens.access_token;
219
+ }
220
+ catch {
221
+ // Refresh failed — fall through to full re-auth
222
+ }
223
+ }
224
+ // Both expired or refresh failed — full re-auth
225
+ tokens = await runOAuthFlow();
226
+ return tokens.access_token;
227
+ }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@avalkit/mcp",
3
+ "version": "0.1.0",
4
+ "description": "MCP server for Avalkit — spend governance and audit for AI agents",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "bin": {
8
+ "avalkit-mcp": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "scripts": {
16
+ "dev": "tsx src/index.ts",
17
+ "build": "tsc",
18
+ "prepublishOnly": "npm run build",
19
+ "start": "node dist/index.js"
20
+ },
21
+ "keywords": [
22
+ "mcp",
23
+ "model-context-protocol",
24
+ "avalkit",
25
+ "ai-agents",
26
+ "spend-governance",
27
+ "ai-cost",
28
+ "claude",
29
+ "cursor"
30
+ ],
31
+ "author": "Erik Bustos <bustos.erik01@gmail.com>",
32
+ "license": "MIT",
33
+ "homepage": "https://avalkit.com",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/avalkit/avalkit.git",
37
+ "directory": "mcp-server"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/avalkit/avalkit/issues"
41
+ },
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@modelcontextprotocol/sdk": "^1.29.0",
50
+ "open": "^11.0.0",
51
+ "zod": "^4.4.3"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^25.6.2",
55
+ "tsx": "^4.21.0",
56
+ "typescript": "^6.0.3"
57
+ }
58
+ }