@monoes/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/README.md +127 -0
- package/dist/connection-pool.d.ts +36 -0
- package/dist/connection-pool.d.ts.map +1 -0
- package/dist/connection-pool.js +273 -0
- package/dist/connection-pool.js.map +1 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +85 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth.d.ts +146 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +318 -0
- package/dist/oauth.js.map +1 -0
- package/dist/prompt-registry.d.ts +90 -0
- package/dist/prompt-registry.d.ts.map +1 -0
- package/dist/prompt-registry.js +209 -0
- package/dist/prompt-registry.js.map +1 -0
- package/dist/rate-limiter.d.ts +86 -0
- package/dist/rate-limiter.d.ts.map +1 -0
- package/dist/rate-limiter.js +197 -0
- package/dist/rate-limiter.js.map +1 -0
- package/dist/resource-registry.d.ts +144 -0
- package/dist/resource-registry.d.ts.map +1 -0
- package/dist/resource-registry.js +405 -0
- package/dist/resource-registry.js.map +1 -0
- package/dist/sampling.d.ts +102 -0
- package/dist/sampling.d.ts.map +1 -0
- package/dist/sampling.js +268 -0
- package/dist/sampling.js.map +1 -0
- package/dist/schema-validator.d.ts +30 -0
- package/dist/schema-validator.d.ts.map +1 -0
- package/dist/schema-validator.js +182 -0
- package/dist/schema-validator.js.map +1 -0
- package/dist/server.d.ts +122 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +829 -0
- package/dist/server.js.map +1 -0
- package/dist/session-manager.d.ts +55 -0
- package/dist/session-manager.d.ts.map +1 -0
- package/dist/session-manager.js +252 -0
- package/dist/session-manager.js.map +1 -0
- package/dist/task-manager.d.ts +81 -0
- package/dist/task-manager.d.ts.map +1 -0
- package/dist/task-manager.js +337 -0
- package/dist/task-manager.js.map +1 -0
- package/dist/tool-registry.d.ts +88 -0
- package/dist/tool-registry.d.ts.map +1 -0
- package/dist/tool-registry.js +353 -0
- package/dist/tool-registry.js.map +1 -0
- package/dist/transport/http.d.ts +71 -0
- package/dist/transport/http.d.ts.map +1 -0
- package/dist/transport/http.js +567 -0
- package/dist/transport/http.js.map +1 -0
- package/dist/transport/index.d.ts +50 -0
- package/dist/transport/index.d.ts.map +1 -0
- package/dist/transport/index.js +181 -0
- package/dist/transport/index.js.map +1 -0
- package/dist/transport/stdio.d.ts +43 -0
- package/dist/transport/stdio.d.ts.map +1 -0
- package/dist/transport/stdio.js +194 -0
- package/dist/transport/stdio.js.map +1 -0
- package/dist/transport/websocket.d.ts +87 -0
- package/dist/transport/websocket.d.ts.map +1 -0
- package/dist/transport/websocket.js +408 -0
- package/dist/transport/websocket.js.map +1 -0
- package/dist/types.d.ts +473 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +40 -0
- package/dist/types.js.map +1 -0
- package/package.json +45 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monoes/mcp - Prompt Registry
|
|
3
|
+
*
|
|
4
|
+
* MCP 2025-11-25 compliant prompt management
|
|
5
|
+
* Supports: list, get, arguments, templates, embedded resources
|
|
6
|
+
*/
|
|
7
|
+
import { EventEmitter } from 'events';
|
|
8
|
+
export class PromptRegistry extends EventEmitter {
|
|
9
|
+
logger;
|
|
10
|
+
prompts = new Map();
|
|
11
|
+
options;
|
|
12
|
+
constructor(logger, options = {}) {
|
|
13
|
+
super();
|
|
14
|
+
this.logger = logger;
|
|
15
|
+
this.options = {
|
|
16
|
+
maxPrompts: options.maxPrompts ?? 1000,
|
|
17
|
+
validateArguments: options.validateArguments ?? true,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Register a prompt
|
|
22
|
+
*/
|
|
23
|
+
register(prompt) {
|
|
24
|
+
if (this.prompts.size >= this.options.maxPrompts) {
|
|
25
|
+
this.logger.error('Maximum prompts reached', { max: this.options.maxPrompts });
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
if (this.prompts.has(prompt.name)) {
|
|
29
|
+
this.logger.warn('Prompt already registered', { name: prompt.name });
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
this.prompts.set(prompt.name, prompt);
|
|
33
|
+
this.logger.debug('Prompt registered', { name: prompt.name });
|
|
34
|
+
this.emit('prompt:registered', { name: prompt.name });
|
|
35
|
+
this.emitListChanged();
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Unregister a prompt
|
|
40
|
+
*/
|
|
41
|
+
unregister(name) {
|
|
42
|
+
if (!this.prompts.has(name)) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
this.prompts.delete(name);
|
|
46
|
+
this.logger.debug('Prompt unregistered', { name });
|
|
47
|
+
this.emit('prompt:unregistered', { name });
|
|
48
|
+
this.emitListChanged();
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* List prompts with pagination
|
|
53
|
+
*/
|
|
54
|
+
list(cursor, pageSize = 50) {
|
|
55
|
+
const allPrompts = Array.from(this.prompts.values()).map((p) => ({
|
|
56
|
+
name: p.name,
|
|
57
|
+
title: p.title,
|
|
58
|
+
description: p.description,
|
|
59
|
+
arguments: p.arguments,
|
|
60
|
+
}));
|
|
61
|
+
let startIndex = 0;
|
|
62
|
+
if (cursor) {
|
|
63
|
+
const decoded = this.decodeCursor(cursor);
|
|
64
|
+
startIndex = decoded.offset;
|
|
65
|
+
}
|
|
66
|
+
const endIndex = Math.min(startIndex + pageSize, allPrompts.length);
|
|
67
|
+
const prompts = allPrompts.slice(startIndex, endIndex);
|
|
68
|
+
const result = { prompts };
|
|
69
|
+
if (endIndex < allPrompts.length) {
|
|
70
|
+
result.nextCursor = this.encodeCursor({ offset: endIndex });
|
|
71
|
+
}
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Get a prompt with arguments
|
|
76
|
+
*/
|
|
77
|
+
async get(name, args = {}) {
|
|
78
|
+
const prompt = this.prompts.get(name);
|
|
79
|
+
if (!prompt) {
|
|
80
|
+
throw new Error(`Prompt not found: ${name}`);
|
|
81
|
+
}
|
|
82
|
+
// Validate required arguments
|
|
83
|
+
if (this.options.validateArguments && prompt.arguments) {
|
|
84
|
+
for (const arg of prompt.arguments) {
|
|
85
|
+
if (arg.required && !(arg.name in args)) {
|
|
86
|
+
throw new Error(`Missing required argument: ${arg.name}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const messages = await prompt.handler(args);
|
|
91
|
+
this.emit('prompt:get', { name, argCount: Object.keys(args).length });
|
|
92
|
+
return {
|
|
93
|
+
description: prompt.description,
|
|
94
|
+
messages,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Get prompt by name
|
|
99
|
+
*/
|
|
100
|
+
getPrompt(name) {
|
|
101
|
+
const prompt = this.prompts.get(name);
|
|
102
|
+
if (!prompt)
|
|
103
|
+
return undefined;
|
|
104
|
+
return {
|
|
105
|
+
name: prompt.name,
|
|
106
|
+
title: prompt.title,
|
|
107
|
+
description: prompt.description,
|
|
108
|
+
arguments: prompt.arguments,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Check if prompt exists
|
|
113
|
+
*/
|
|
114
|
+
hasPrompt(name) {
|
|
115
|
+
return this.prompts.has(name);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Get prompt count
|
|
119
|
+
*/
|
|
120
|
+
getPromptCount() {
|
|
121
|
+
return this.prompts.size;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Get stats
|
|
125
|
+
*/
|
|
126
|
+
getStats() {
|
|
127
|
+
let promptsWithArgs = 0;
|
|
128
|
+
for (const prompt of this.prompts.values()) {
|
|
129
|
+
if (prompt.arguments && prompt.arguments.length > 0) {
|
|
130
|
+
promptsWithArgs++;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
totalPrompts: this.prompts.size,
|
|
135
|
+
promptsWithArgs,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Encode cursor for pagination
|
|
140
|
+
*/
|
|
141
|
+
encodeCursor(data) {
|
|
142
|
+
return Buffer.from(JSON.stringify(data)).toString('base64');
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Decode cursor for pagination
|
|
146
|
+
*/
|
|
147
|
+
decodeCursor(cursor) {
|
|
148
|
+
try {
|
|
149
|
+
return JSON.parse(Buffer.from(cursor, 'base64').toString('utf-8'));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return { offset: 0 };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Emit listChanged notification
|
|
157
|
+
*/
|
|
158
|
+
emitListChanged() {
|
|
159
|
+
this.emit('prompts:listChanged');
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
export function createPromptRegistry(logger, options) {
|
|
163
|
+
return new PromptRegistry(logger, options);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Helper to define a prompt
|
|
167
|
+
*/
|
|
168
|
+
export function definePrompt(name, description, handler, options) {
|
|
169
|
+
return {
|
|
170
|
+
name,
|
|
171
|
+
description,
|
|
172
|
+
title: options?.title,
|
|
173
|
+
arguments: options?.arguments,
|
|
174
|
+
handler,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Helper to create a text message
|
|
179
|
+
*/
|
|
180
|
+
export function textMessage(role, text) {
|
|
181
|
+
return {
|
|
182
|
+
role,
|
|
183
|
+
content: {
|
|
184
|
+
type: 'text',
|
|
185
|
+
text,
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Helper to create a message with embedded resource
|
|
191
|
+
*/
|
|
192
|
+
export function resourceMessage(role, resource) {
|
|
193
|
+
return {
|
|
194
|
+
role,
|
|
195
|
+
content: {
|
|
196
|
+
type: 'resource',
|
|
197
|
+
resource,
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Template string interpolation for prompts
|
|
203
|
+
*/
|
|
204
|
+
export function interpolate(template, args) {
|
|
205
|
+
return template.replace(/\{(\w+)\}/g, (match, key) => {
|
|
206
|
+
return args[key] ?? match;
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=prompt-registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-registry.js","sourceRoot":"","sources":["../src/prompt-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AA2BtC,MAAM,OAAO,cAAe,SAAQ,YAAY;IAM3B,MAAM;IALjB,OAAO,GAAkC,IAAI,GAAG,EAAE,CAAC;IAE1C,OAAO,CAAkC;IAE1D,YACmB,MAAe,EAChC,OAAO,GAA0B,EAAE;QAEnC,KAAK,EAAE,CAAC;sBAHS,MAAM;QAIvB,IAAI,CAAC,OAAO,GAAG;YACb,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,IAAI;YACtC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,IAAI,IAAI;SACrD,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,MAAwB;QAC/B,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;YACjD,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yBAAyB,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;YAC/E,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI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ED;;GAEG;AACH,MAAM,UAAU,eAAe,CAC7B,IAA0B,EAC1B,QAAyB;IAEzB,OAAO;QACL,IAAI;QACJ,OAAO,EAAE;YACP,IAAI,EAAE,UAAU;YAChB,QAAQ;SACW;KACtB,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CACzB,QAAgB,EAChB,IAA4B;IAE5B,OAAO,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACnD,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monoes/mcp - Rate Limiter
|
|
3
|
+
*
|
|
4
|
+
* Token bucket rate limiting for DoS protection
|
|
5
|
+
*/
|
|
6
|
+
import { EventEmitter } from 'events';
|
|
7
|
+
import type { ILogger } from './types.js';
|
|
8
|
+
export interface RateLimitConfig {
|
|
9
|
+
/** Requests per second */
|
|
10
|
+
requestsPerSecond: number;
|
|
11
|
+
/** Burst size (max tokens) */
|
|
12
|
+
burstSize: number;
|
|
13
|
+
/** Per-session limits (if different from global) */
|
|
14
|
+
perSessionLimit?: number;
|
|
15
|
+
/** Cleanup interval for expired sessions */
|
|
16
|
+
cleanupInterval?: number;
|
|
17
|
+
}
|
|
18
|
+
export interface RateLimitResult {
|
|
19
|
+
allowed: boolean;
|
|
20
|
+
remaining: number;
|
|
21
|
+
resetIn: number;
|
|
22
|
+
retryAfter?: number;
|
|
23
|
+
}
|
|
24
|
+
export declare class RateLimiter extends EventEmitter {
|
|
25
|
+
private readonly logger;
|
|
26
|
+
private readonly config;
|
|
27
|
+
private globalBucket;
|
|
28
|
+
private sessionBuckets;
|
|
29
|
+
private cleanupTimer?;
|
|
30
|
+
constructor(logger: ILogger, config?: Partial<RateLimitConfig>);
|
|
31
|
+
/**
|
|
32
|
+
* Check if request is allowed (global limit)
|
|
33
|
+
*/
|
|
34
|
+
checkGlobal(): RateLimitResult;
|
|
35
|
+
/**
|
|
36
|
+
* Check if request is allowed (per-session limit)
|
|
37
|
+
*/
|
|
38
|
+
checkSession(sessionId: string): RateLimitResult;
|
|
39
|
+
/**
|
|
40
|
+
* Check both global and session limits
|
|
41
|
+
*/
|
|
42
|
+
check(sessionId?: string): RateLimitResult;
|
|
43
|
+
/**
|
|
44
|
+
* Consume a token (call after request is processed)
|
|
45
|
+
*/
|
|
46
|
+
consume(sessionId?: string): void;
|
|
47
|
+
/**
|
|
48
|
+
* Reset session bucket
|
|
49
|
+
*/
|
|
50
|
+
resetSession(sessionId: string): void;
|
|
51
|
+
/**
|
|
52
|
+
* Get current stats
|
|
53
|
+
*/
|
|
54
|
+
getStats(): {
|
|
55
|
+
globalTokens: number;
|
|
56
|
+
globalBurstSize: number;
|
|
57
|
+
sessionCount: number;
|
|
58
|
+
config: RateLimitConfig;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Destroy the rate limiter
|
|
62
|
+
*/
|
|
63
|
+
destroy(): void;
|
|
64
|
+
/**
|
|
65
|
+
* Check bucket and refill tokens
|
|
66
|
+
*/
|
|
67
|
+
private checkBucket;
|
|
68
|
+
/**
|
|
69
|
+
* Refill tokens based on elapsed time
|
|
70
|
+
*/
|
|
71
|
+
private refillBucket;
|
|
72
|
+
/**
|
|
73
|
+
* Consume a token from bucket
|
|
74
|
+
*/
|
|
75
|
+
private consumeFromBucket;
|
|
76
|
+
/**
|
|
77
|
+
* Start cleanup timer for expired sessions
|
|
78
|
+
*/
|
|
79
|
+
private startCleanup;
|
|
80
|
+
}
|
|
81
|
+
export declare function createRateLimiter(logger: ILogger, config?: Partial<RateLimitConfig>): RateLimiter;
|
|
82
|
+
/**
|
|
83
|
+
* Express/Connect middleware for rate limiting
|
|
84
|
+
*/
|
|
85
|
+
export declare function rateLimitMiddleware(rateLimiter: RateLimiter): (req: any, res: any, next: () => void) => void;
|
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,SAAS,EAAE,MAAM,GAAG,IAAI,CAGpC;IAED;;OAEG;IACH,QAAQ,IAAI;QACV,YAAY,EAAE,MAAM,CAAC;QACrB,eAAe,EAAE,MAAM,CAAC;QACxB,YAAY,EAAE,MAAM,CAAC;QACrB,MAAM,EAAE,eAAe,CAAC;KACzB,CAQA;IAED;;OAEG;IACH,OAAO,IAAI,IAAI,CAOd;IAED;;OAEG;IACH,OAAO,CAAC,WAAW;IA2BnB;;OAEG;IACH,OAAO,CAAC,YAAY;IASpB;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAMzB;;OAEG;IACH,OAAO,CAAC,YAAY;CAarB;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,OAAO,EACf,MAAM,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,GAChC,WAAW,CAEb;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,WAAW,SAC7C,GAAG,OAAO,GAAG,QAAQ,MAAM,IAAI,UAwB7C"}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monoes/mcp - Rate Limiter
|
|
3
|
+
*
|
|
4
|
+
* Token bucket rate limiting for DoS protection
|
|
5
|
+
*/
|
|
6
|
+
import { EventEmitter } from 'events';
|
|
7
|
+
const DEFAULT_CONFIG = {
|
|
8
|
+
requestsPerSecond: 100,
|
|
9
|
+
burstSize: 200,
|
|
10
|
+
perSessionLimit: 50,
|
|
11
|
+
cleanupInterval: 60000, // 1 minute
|
|
12
|
+
};
|
|
13
|
+
export class RateLimiter extends EventEmitter {
|
|
14
|
+
logger;
|
|
15
|
+
config;
|
|
16
|
+
globalBucket;
|
|
17
|
+
sessionBuckets = new Map();
|
|
18
|
+
cleanupTimer;
|
|
19
|
+
constructor(logger, config = {}) {
|
|
20
|
+
super();
|
|
21
|
+
this.logger = logger;
|
|
22
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
23
|
+
// Initialize global bucket
|
|
24
|
+
this.globalBucket = {
|
|
25
|
+
tokens: this.config.burstSize,
|
|
26
|
+
lastRefill: Date.now(),
|
|
27
|
+
};
|
|
28
|
+
this.startCleanup();
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Check if request is allowed (global limit)
|
|
32
|
+
*/
|
|
33
|
+
checkGlobal() {
|
|
34
|
+
return this.checkBucket(this.globalBucket, this.config.requestsPerSecond, this.config.burstSize);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Check if request is allowed (per-session limit)
|
|
38
|
+
*/
|
|
39
|
+
checkSession(sessionId) {
|
|
40
|
+
let bucket = this.sessionBuckets.get(sessionId);
|
|
41
|
+
if (!bucket) {
|
|
42
|
+
bucket = {
|
|
43
|
+
tokens: this.config.perSessionLimit,
|
|
44
|
+
lastRefill: Date.now(),
|
|
45
|
+
};
|
|
46
|
+
this.sessionBuckets.set(sessionId, bucket);
|
|
47
|
+
}
|
|
48
|
+
return this.checkBucket(bucket, this.config.perSessionLimit / 10, // Refill rate (10 seconds to full)
|
|
49
|
+
this.config.perSessionLimit);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Check both global and session limits
|
|
53
|
+
*/
|
|
54
|
+
check(sessionId) {
|
|
55
|
+
const globalResult = this.checkGlobal();
|
|
56
|
+
if (!globalResult.allowed) {
|
|
57
|
+
this.emit('rate-limit:global', { remaining: globalResult.remaining });
|
|
58
|
+
return globalResult;
|
|
59
|
+
}
|
|
60
|
+
if (sessionId) {
|
|
61
|
+
const sessionResult = this.checkSession(sessionId);
|
|
62
|
+
if (!sessionResult.allowed) {
|
|
63
|
+
this.emit('rate-limit:session', { sessionId, remaining: sessionResult.remaining });
|
|
64
|
+
return sessionResult;
|
|
65
|
+
}
|
|
66
|
+
return sessionResult;
|
|
67
|
+
}
|
|
68
|
+
return globalResult;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Consume a token (call after request is processed)
|
|
72
|
+
*/
|
|
73
|
+
consume(sessionId) {
|
|
74
|
+
this.consumeFromBucket(this.globalBucket);
|
|
75
|
+
if (sessionId) {
|
|
76
|
+
const bucket = this.sessionBuckets.get(sessionId);
|
|
77
|
+
if (bucket) {
|
|
78
|
+
this.consumeFromBucket(bucket);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Reset session bucket
|
|
84
|
+
*/
|
|
85
|
+
resetSession(sessionId) {
|
|
86
|
+
this.sessionBuckets.delete(sessionId);
|
|
87
|
+
this.logger.debug('Rate limit session reset', { sessionId });
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Get current stats
|
|
91
|
+
*/
|
|
92
|
+
getStats() {
|
|
93
|
+
this.refillBucket(this.globalBucket, this.config.requestsPerSecond, this.config.burstSize);
|
|
94
|
+
return {
|
|
95
|
+
globalTokens: Math.floor(this.globalBucket.tokens),
|
|
96
|
+
globalBurstSize: this.config.burstSize,
|
|
97
|
+
sessionCount: this.sessionBuckets.size,
|
|
98
|
+
config: this.config,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Destroy the rate limiter
|
|
103
|
+
*/
|
|
104
|
+
destroy() {
|
|
105
|
+
if (this.cleanupTimer) {
|
|
106
|
+
clearInterval(this.cleanupTimer);
|
|
107
|
+
this.cleanupTimer = undefined;
|
|
108
|
+
}
|
|
109
|
+
this.sessionBuckets.clear();
|
|
110
|
+
this.removeAllListeners();
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Check bucket and refill tokens
|
|
114
|
+
*/
|
|
115
|
+
checkBucket(bucket, refillRate, maxTokens) {
|
|
116
|
+
this.refillBucket(bucket, refillRate, maxTokens);
|
|
117
|
+
if (bucket.tokens >= 1) {
|
|
118
|
+
return {
|
|
119
|
+
allowed: true,
|
|
120
|
+
remaining: Math.floor(bucket.tokens) - 1,
|
|
121
|
+
resetIn: Math.ceil((maxTokens - bucket.tokens) / refillRate * 1000),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// Calculate when bucket will have 1 token
|
|
125
|
+
const tokensNeeded = 1 - bucket.tokens;
|
|
126
|
+
const retryAfter = Math.ceil(tokensNeeded / refillRate);
|
|
127
|
+
return {
|
|
128
|
+
allowed: false,
|
|
129
|
+
remaining: 0,
|
|
130
|
+
resetIn: retryAfter * 1000,
|
|
131
|
+
retryAfter,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Refill tokens based on elapsed time
|
|
136
|
+
*/
|
|
137
|
+
refillBucket(bucket, refillRate, maxTokens) {
|
|
138
|
+
const now = Date.now();
|
|
139
|
+
const elapsed = (now - bucket.lastRefill) / 1000; // seconds
|
|
140
|
+
const tokensToAdd = elapsed * refillRate;
|
|
141
|
+
bucket.tokens = Math.min(maxTokens, bucket.tokens + tokensToAdd);
|
|
142
|
+
bucket.lastRefill = now;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Consume a token from bucket
|
|
146
|
+
*/
|
|
147
|
+
consumeFromBucket(bucket) {
|
|
148
|
+
if (bucket.tokens >= 1) {
|
|
149
|
+
bucket.tokens -= 1;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Start cleanup timer for expired sessions
|
|
154
|
+
*/
|
|
155
|
+
startCleanup() {
|
|
156
|
+
this.cleanupTimer = setInterval(() => {
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
const expireTime = this.config.cleanupInterval * 2;
|
|
159
|
+
for (const [sessionId, bucket] of this.sessionBuckets) {
|
|
160
|
+
if (now - bucket.lastRefill > expireTime) {
|
|
161
|
+
this.sessionBuckets.delete(sessionId);
|
|
162
|
+
this.logger.debug('Rate limit session expired', { sessionId });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}, this.config.cleanupInterval);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
export function createRateLimiter(logger, config) {
|
|
169
|
+
return new RateLimiter(logger, config);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Express/Connect middleware for rate limiting
|
|
173
|
+
*/
|
|
174
|
+
export function rateLimitMiddleware(rateLimiter) {
|
|
175
|
+
return (req, res, next) => {
|
|
176
|
+
const sessionId = req.headers['x-session-id'] || req.ip;
|
|
177
|
+
const result = rateLimiter.check(sessionId);
|
|
178
|
+
res.setHeader('X-RateLimit-Remaining', result.remaining);
|
|
179
|
+
res.setHeader('X-RateLimit-Reset', Math.ceil(Date.now() / 1000) + Math.ceil(result.resetIn / 1000));
|
|
180
|
+
if (!result.allowed) {
|
|
181
|
+
res.setHeader('Retry-After', result.retryAfter);
|
|
182
|
+
res.status(429).json({
|
|
183
|
+
jsonrpc: '2.0',
|
|
184
|
+
id: null,
|
|
185
|
+
error: {
|
|
186
|
+
code: -32000,
|
|
187
|
+
message: 'Rate limit exceeded',
|
|
188
|
+
data: { retryAfter: result.retryAfter },
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
rateLimiter.consume(sessionId);
|
|
194
|
+
next();
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
//# sourceMappingURL=rate-limiter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":["../src/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AA0BtC,MAAM,cAAc,GAAoB;IACtC,iBAAiB,EAAE,GAAG;IACtB,SAAS,EAAE,GAAG;IACd,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,KAAK,EAAE,WAAW;CACpC,CAAC;AAEF,MAAM,OAAO,WAAY,SAAQ,YAAY;IAOxB,MAAM;IANR,MAAM,CAA4B;IAC3C,YAAY,CAAc;IAC1B,cAAc,GAA6B,IAAI,GAAG,EAAE,CAAC;IACrD,YAAY,CAA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*/
|
|
7
|
+
import { EventEmitter } from 'events';
|
|
8
|
+
import type { MCPResource, ResourceContent, ResourceTemplate, ResourceListResult, ResourceReadResult, ILogger, ContentAnnotations } from './types.js';
|
|
9
|
+
export type ResourceHandler = (uri: string) => Promise<ResourceContent[]>;
|
|
10
|
+
export type SubscriptionCallback = (uri: string, content: ResourceContent[]) => void;
|
|
11
|
+
export interface ResourceRegistryOptions {
|
|
12
|
+
enableSubscriptions?: boolean;
|
|
13
|
+
maxSubscriptionsPerResource?: number;
|
|
14
|
+
cacheEnabled?: boolean;
|
|
15
|
+
cacheTTL?: number;
|
|
16
|
+
maxCacheSize?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare class ResourceRegistry extends EventEmitter {
|
|
19
|
+
private readonly logger;
|
|
20
|
+
private resources;
|
|
21
|
+
private templates;
|
|
22
|
+
private handlers;
|
|
23
|
+
private subscriptions;
|
|
24
|
+
private cache;
|
|
25
|
+
private subscriptionCounter;
|
|
26
|
+
private readonly options;
|
|
27
|
+
constructor(logger: ILogger, options?: ResourceRegistryOptions);
|
|
28
|
+
/**
|
|
29
|
+
* Register a static resource
|
|
30
|
+
*/
|
|
31
|
+
registerResource(resource: MCPResource, handler: ResourceHandler): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Register a resource template (dynamic URIs)
|
|
34
|
+
*/
|
|
35
|
+
registerTemplate(template: ResourceTemplate, handler: ResourceHandler): boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Unregister a resource
|
|
38
|
+
*/
|
|
39
|
+
unregisterResource(uri: string): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* List resources with pagination
|
|
42
|
+
*/
|
|
43
|
+
list(cursor?: string, pageSize?: number): ResourceListResult;
|
|
44
|
+
/**
|
|
45
|
+
* Read resource content
|
|
46
|
+
*/
|
|
47
|
+
read(uri: string): Promise<ResourceReadResult>;
|
|
48
|
+
/**
|
|
49
|
+
* Subscribe to resource updates
|
|
50
|
+
*/
|
|
51
|
+
subscribe(uri: string, callback: SubscriptionCallback): string;
|
|
52
|
+
/**
|
|
53
|
+
* Unsubscribe from resource updates
|
|
54
|
+
*/
|
|
55
|
+
unsubscribe(subscriptionId: string): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Notify subscribers of resource update
|
|
58
|
+
*/
|
|
59
|
+
notifyUpdate(uri: string): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Get resource by URI
|
|
62
|
+
*/
|
|
63
|
+
getResource(uri: string): MCPResource | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* Check if resource exists
|
|
66
|
+
*/
|
|
67
|
+
hasResource(uri: string): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* Get resource count
|
|
70
|
+
*/
|
|
71
|
+
getResourceCount(): number;
|
|
72
|
+
/**
|
|
73
|
+
* Get all templates
|
|
74
|
+
*/
|
|
75
|
+
getTemplates(): ResourceTemplate[];
|
|
76
|
+
/**
|
|
77
|
+
* Get subscription count for a resource
|
|
78
|
+
*/
|
|
79
|
+
getSubscriptionCount(uri: string): number;
|
|
80
|
+
/**
|
|
81
|
+
* Get stats
|
|
82
|
+
*/
|
|
83
|
+
getStats(): {
|
|
84
|
+
totalResources: number;
|
|
85
|
+
totalTemplates: number;
|
|
86
|
+
totalSubscriptions: number;
|
|
87
|
+
cacheSize: number;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Clear cache
|
|
91
|
+
*/
|
|
92
|
+
clearCache(): void;
|
|
93
|
+
/**
|
|
94
|
+
* Find handler for template URI
|
|
95
|
+
*/
|
|
96
|
+
private findTemplateHandler;
|
|
97
|
+
/**
|
|
98
|
+
* Escape regex metacharacters to prevent ReDoS attacks
|
|
99
|
+
* SECURITY: Critical for preventing regex denial of service
|
|
100
|
+
*/
|
|
101
|
+
private escapeRegex;
|
|
102
|
+
/**
|
|
103
|
+
* Check if URI matches any template
|
|
104
|
+
* SECURITY: Uses escaped regex to prevent ReDoS
|
|
105
|
+
*/
|
|
106
|
+
private matchesTemplate;
|
|
107
|
+
/**
|
|
108
|
+
* Encode cursor for pagination
|
|
109
|
+
*/
|
|
110
|
+
private encodeCursor;
|
|
111
|
+
/**
|
|
112
|
+
* Decode cursor for pagination
|
|
113
|
+
*/
|
|
114
|
+
private decodeCursor;
|
|
115
|
+
/**
|
|
116
|
+
* Emit listChanged notification
|
|
117
|
+
*/
|
|
118
|
+
private emitListChanged;
|
|
119
|
+
}
|
|
120
|
+
export declare function createResourceRegistry(logger: ILogger, options?: ResourceRegistryOptions): ResourceRegistry;
|
|
121
|
+
/**
|
|
122
|
+
* Helper to create a static text resource
|
|
123
|
+
*/
|
|
124
|
+
export declare function createTextResource(uri: string, name: string, text: string, options?: {
|
|
125
|
+
description?: string;
|
|
126
|
+
mimeType?: string;
|
|
127
|
+
annotations?: ContentAnnotations;
|
|
128
|
+
}): {
|
|
129
|
+
resource: MCPResource;
|
|
130
|
+
handler: ResourceHandler;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Helper to create a file resource
|
|
134
|
+
* SECURITY: Validates path to prevent path traversal attacks
|
|
135
|
+
*/
|
|
136
|
+
export declare function createFileResource(uri: string, name: string, filePath: string, options?: {
|
|
137
|
+
description?: string;
|
|
138
|
+
mimeType?: string;
|
|
139
|
+
allowedBasePaths?: string[];
|
|
140
|
+
}): {
|
|
141
|
+
resource: MCPResource;
|
|
142
|
+
handler: ResourceHandler;
|
|
143
|
+
};
|
|
144
|
+
//# sourceMappingURL=resource-registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-registry.d.ts","sourceRoot":"","sources":["../src/resource-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,kBAAkB,EAClB,OAAO,EACP,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAEpB,M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