@mcp-ts/sdk 1.3.5 → 1.3.6

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.
@@ -0,0 +1,227 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ import { StorageBackend, SessionData } from './types.js';
3
+ import { SESSION_TTL_SECONDS } from '../../shared/constants.js';
4
+
5
+ export class SupabaseStorageBackend implements StorageBackend {
6
+ private readonly DEFAULT_TTL = SESSION_TTL_SECONDS;
7
+
8
+ constructor(private supabase: SupabaseClient) {}
9
+
10
+ async init(): Promise<void> {
11
+ // Validate that the table exists
12
+ const { error } = await this.supabase
13
+ .from('mcp_sessions')
14
+ .select('session_id')
15
+ .limit(0);
16
+
17
+ if (error) {
18
+ // Postgres error code 42P01 is "relation does not exist"
19
+ if (error.code === '42P01') {
20
+ throw new Error(
21
+ '[SupabaseStorage] Table "mcp_sessions" not found in your database. ' +
22
+ 'Please run "npx mcp-ts supabase-init" in your project to set up the required table and RLS policies.'
23
+ );
24
+ }
25
+ throw new Error(`[SupabaseStorage] Initialization check failed: ${error.message}`);
26
+ }
27
+
28
+ console.log('[mcp-ts][Storage] Supabase: ✓ "mcp_sessions" table verified.');
29
+ }
30
+
31
+ generateSessionId(): string {
32
+ return crypto.randomUUID();
33
+ }
34
+
35
+ private mapRowToSessionData(row: any): SessionData {
36
+ return {
37
+ sessionId: row.session_id,
38
+ serverId: row.server_id,
39
+ serverName: row.server_name,
40
+ serverUrl: row.server_url,
41
+ transportType: row.transport_type,
42
+ callbackUrl: row.callback_url,
43
+ createdAt: new Date(row.created_at).getTime(),
44
+ identity: row.identity,
45
+ headers: row.headers,
46
+ active: row.active,
47
+ clientInformation: row.client_information,
48
+ tokens: row.tokens,
49
+ codeVerifier: row.code_verifier,
50
+ clientId: row.client_id,
51
+ };
52
+ }
53
+
54
+ async createSession(session: SessionData, ttl?: number): Promise<void> {
55
+ const { sessionId, identity } = session;
56
+ if (!sessionId || !identity) throw new Error('identity and sessionId required');
57
+
58
+ const effectiveTtl = ttl ?? this.DEFAULT_TTL;
59
+ const expiresAt = new Date(Date.now() + effectiveTtl * 1000).toISOString();
60
+
61
+ const { error } = await this.supabase
62
+ .from('mcp_sessions')
63
+ .insert({
64
+ session_id: sessionId,
65
+ user_id: identity, // Maps user_id to identity to support RLS using auth.uid()
66
+ server_id: session.serverId,
67
+ server_name: session.serverName,
68
+ server_url: session.serverUrl,
69
+ transport_type: session.transportType,
70
+ callback_url: session.callbackUrl,
71
+ created_at: new Date(session.createdAt || Date.now()).toISOString(),
72
+ identity: identity,
73
+ headers: session.headers,
74
+ active: session.active ?? false,
75
+ client_information: session.clientInformation,
76
+ tokens: session.tokens,
77
+ code_verifier: session.codeVerifier,
78
+ client_id: session.clientId,
79
+ expires_at: expiresAt
80
+ });
81
+
82
+ if (error) {
83
+ // Postgres error code 23505 is unique violation
84
+ if (error.code === '23505') {
85
+ throw new Error(`Session ${sessionId} already exists`);
86
+ }
87
+ throw new Error(`Failed to create session in Supabase: ${error.message}`);
88
+ }
89
+ }
90
+
91
+ async updateSession(identity: string, sessionId: string, data: Partial<SessionData>, ttl?: number): Promise<void> {
92
+ const effectiveTtl = ttl ?? this.DEFAULT_TTL;
93
+ const expiresAt = new Date(Date.now() + effectiveTtl * 1000).toISOString();
94
+
95
+ // Convert the camelCase keys to snake_case for Supabase
96
+ const updateData: any = {
97
+ expires_at: expiresAt,
98
+ updated_at: new Date().toISOString()
99
+ };
100
+
101
+ if ('serverId' in data) updateData.server_id = data.serverId;
102
+ if ('serverName' in data) updateData.server_name = data.serverName;
103
+ if ('serverUrl' in data) updateData.server_url = data.serverUrl;
104
+ if ('transportType' in data) updateData.transport_type = data.transportType;
105
+ if ('callbackUrl' in data) updateData.callback_url = data.callbackUrl;
106
+ if ('active' in data) updateData.active = data.active;
107
+ if ('headers' in data) updateData.headers = data.headers;
108
+ if ('clientInformation' in data) updateData.client_information = data.clientInformation;
109
+ if ('tokens' in data) updateData.tokens = data.tokens;
110
+ if ('codeVerifier' in data) updateData.code_verifier = data.codeVerifier;
111
+ if ('clientId' in data) updateData.client_id = data.clientId;
112
+
113
+ const { data: updatedRows, error } = await this.supabase
114
+ .from('mcp_sessions')
115
+ .update(updateData)
116
+ .eq('identity', identity)
117
+ .eq('session_id', sessionId)
118
+ .select('id');
119
+
120
+ if (error) {
121
+ throw new Error(`Failed to update session: ${error.message}`);
122
+ }
123
+
124
+ if (!updatedRows || updatedRows.length === 0) {
125
+ throw new Error(`Session ${sessionId} not found for identity ${identity}`);
126
+ }
127
+ }
128
+
129
+ async getSession(identity: string, sessionId: string): Promise<SessionData | null> {
130
+ const { data, error } = await this.supabase
131
+ .from('mcp_sessions')
132
+ .select('*')
133
+ .eq('identity', identity)
134
+ .eq('session_id', sessionId)
135
+ .maybeSingle();
136
+
137
+ if (error) {
138
+ console.error('[SupabaseStorage] Failed to get session:', error);
139
+ return null;
140
+ }
141
+
142
+ if (!data) return null;
143
+
144
+ return this.mapRowToSessionData(data);
145
+ }
146
+
147
+ async getIdentitySessionsData(identity: string): Promise<SessionData[]> {
148
+ const { data, error } = await this.supabase
149
+ .from('mcp_sessions')
150
+ .select('*')
151
+ .eq('identity', identity);
152
+
153
+ if (error) {
154
+ console.error(`[SupabaseStorage] Failed to get session data for ${identity}:`, error);
155
+ return [];
156
+ }
157
+
158
+ return data.map(row => this.mapRowToSessionData(row));
159
+ }
160
+
161
+ async removeSession(identity: string, sessionId: string): Promise<void> {
162
+ const { error } = await this.supabase
163
+ .from('mcp_sessions')
164
+ .delete()
165
+ .eq('identity', identity)
166
+ .eq('session_id', sessionId);
167
+
168
+ if (error) {
169
+ console.error('[SupabaseStorage] Failed to remove session:', error);
170
+ }
171
+ }
172
+
173
+ async getIdentityMcpSessions(identity: string): Promise<string[]> {
174
+ const { data, error } = await this.supabase
175
+ .from('mcp_sessions')
176
+ .select('session_id')
177
+ .eq('identity', identity);
178
+
179
+ if (error) {
180
+ console.error(`[SupabaseStorage] Failed to get sessions for ${identity}:`, error);
181
+ return [];
182
+ }
183
+
184
+ return data.map(row => row.session_id);
185
+ }
186
+
187
+ async getAllSessionIds(): Promise<string[]> {
188
+ const { data, error } = await this.supabase
189
+ .from('mcp_sessions')
190
+ .select('session_id');
191
+
192
+ if (error) {
193
+ console.error('[SupabaseStorage] Failed to get all sessions:', error);
194
+ return [];
195
+ }
196
+
197
+ return data.map(row => row.session_id);
198
+ }
199
+
200
+ async clearAll(): Promise<void> {
201
+ // Warning: This deletes everything. Typically only used in testing.
202
+ const { error } = await this.supabase
203
+ .from('mcp_sessions')
204
+ .delete()
205
+ .neq('session_id', ''); // Delete all rows trick
206
+
207
+ if (error) {
208
+ console.error('[SupabaseStorage] Failed to clear sessions:', error);
209
+ }
210
+ }
211
+
212
+ async cleanupExpiredSessions(): Promise<void> {
213
+ const { error } = await this.supabase
214
+ .from('mcp_sessions')
215
+ .delete()
216
+ .lt('expires_at', new Date().toISOString());
217
+
218
+ if (error) {
219
+ console.error('[SupabaseStorage] Failed to cleanup expired sessions:', error);
220
+ }
221
+ }
222
+
223
+ async disconnect(): Promise<void> {
224
+ // Supabase client handles its own connection pooling over HTTP,
225
+ // there is no explicit disconnect method.
226
+ }
227
+ }
@@ -1,28 +1,28 @@
1
- import type { McpConnectionEvent, McpObservabilityEvent } from './events.js';
2
- import type { McpRpcResponse } from './types.js';
3
-
4
- export function isRpcResponseEvent(
5
- event: McpConnectionEvent | McpObservabilityEvent | McpRpcResponse
6
- ): event is McpRpcResponse {
7
- return 'id' in event && ('result' in event || 'error' in event);
8
- }
9
-
10
- export function isConnectionEvent(
11
- event: McpConnectionEvent | McpObservabilityEvent | McpRpcResponse
12
- ): event is McpConnectionEvent {
13
- if (!('type' in event)) {
14
- return false;
15
- }
16
-
17
- switch (event.type) {
18
- case 'state_changed':
19
- case 'tools_discovered':
20
- case 'auth_required':
21
- case 'error':
22
- case 'disconnected':
23
- case 'progress':
24
- return true;
25
- default:
26
- return false;
27
- }
28
- }
1
+ import type { McpConnectionEvent, McpObservabilityEvent } from './events.js';
2
+ import type { McpRpcResponse } from './types.js';
3
+
4
+ export function isRpcResponseEvent(
5
+ event: McpConnectionEvent | McpObservabilityEvent | McpRpcResponse
6
+ ): event is McpRpcResponse {
7
+ return 'id' in event && ('result' in event || 'error' in event);
8
+ }
9
+
10
+ export function isConnectionEvent(
11
+ event: McpConnectionEvent | McpObservabilityEvent | McpRpcResponse
12
+ ): event is McpConnectionEvent {
13
+ if (!('type' in event)) {
14
+ return false;
15
+ }
16
+
17
+ switch (event.type) {
18
+ case 'state_changed':
19
+ case 'tools_discovered':
20
+ case 'auth_required':
21
+ case 'error':
22
+ case 'disconnected':
23
+ case 'progress':
24
+ return true;
25
+ default:
26
+ return false;
27
+ }
28
+ }
@@ -0,0 +1,84 @@
1
+ -- Create the mcp_sessions table
2
+ CREATE TABLE IF NOT EXISTS public.mcp_sessions (
3
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
4
+ session_id TEXT NOT NULL UNIQUE,
5
+ user_id TEXT NOT NULL, -- Will store the Next.js user's ID or identity
6
+ server_id TEXT,
7
+ server_name TEXT,
8
+ server_url TEXT NOT NULL,
9
+ transport_type TEXT NOT NULL,
10
+ callback_url TEXT NOT NULL,
11
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
12
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
13
+ expires_at TIMESTAMPTZ NOT NULL,
14
+ active BOOLEAN DEFAULT false,
15
+ identity TEXT NOT NULL,
16
+ headers JSONB,
17
+ client_information JSONB,
18
+ tokens JSONB,
19
+ code_verifier TEXT,
20
+ client_id TEXT
21
+ );
22
+
23
+ -- Add an index on identity and user_id for faster lookups
24
+ CREATE INDEX IF NOT EXISTS idx_mcp_sessions_identity ON public.mcp_sessions(identity);
25
+ CREATE INDEX IF NOT EXISTS idx_mcp_sessions_user_id ON public.mcp_sessions(user_id);
26
+ -- Add an index on expires_at to speed up the cleanup job
27
+ CREATE INDEX IF NOT EXISTS idx_mcp_sessions_expires_at ON public.mcp_sessions(expires_at);
28
+
29
+ -- Trigger to automatically update the 'updated_at' column
30
+ CREATE OR REPLACE FUNCTION public.set_current_timestamp_updated_at()
31
+ RETURNS TRIGGER AS $$
32
+ BEGIN
33
+ NEW.updated_at = now();
34
+ RETURN NEW;
35
+ END;
36
+ $$ LANGUAGE plpgsql;
37
+
38
+ DROP TRIGGER IF EXISTS trg_mcp_sessions_updated_at ON public.mcp_sessions;
39
+ CREATE TRIGGER trg_mcp_sessions_updated_at
40
+ BEFORE UPDATE ON public.mcp_sessions
41
+ FOR EACH ROW
42
+ EXECUTE FUNCTION public.set_current_timestamp_updated_at();
43
+
44
+ -- Enable Row Level Security (RLS)
45
+ ALTER TABLE public.mcp_sessions ENABLE ROW LEVEL SECURITY;
46
+
47
+ -- Policy 1: Users can read their own sessions
48
+ CREATE POLICY "Users can view their own sessions"
49
+ ON public.mcp_sessions
50
+ FOR SELECT
51
+ TO authenticated
52
+ USING (
53
+ auth.uid()::text = user_id OR auth.uid()::text = identity
54
+ );
55
+
56
+ -- Policy 2: Users can insert their own sessions
57
+ CREATE POLICY "Users can insert their own sessions"
58
+ ON public.mcp_sessions
59
+ FOR INSERT
60
+ TO authenticated
61
+ WITH CHECK (
62
+ auth.uid()::text = user_id OR auth.uid()::text = identity
63
+ );
64
+
65
+ -- Policy 3: Users can update their own sessions
66
+ CREATE POLICY "Users can update their own sessions"
67
+ ON public.mcp_sessions
68
+ FOR UPDATE
69
+ TO authenticated
70
+ USING (
71
+ auth.uid()::text = user_id OR auth.uid()::text = identity
72
+ )
73
+ WITH CHECK (
74
+ auth.uid()::text = user_id OR auth.uid()::text = identity
75
+ );
76
+
77
+ -- Policy 4: Users can delete their own sessions
78
+ CREATE POLICY "Users can delete their own sessions"
79
+ ON public.mcp_sessions
80
+ FOR DELETE
81
+ TO authenticated
82
+ USING (
83
+ auth.uid()::text = user_id OR auth.uid()::text = identity
84
+ );