Skip to content

Commit 4ed3d4d

Browse files
authored
Merge pull request #1 from ooojustin/mcp-proxy-logging
Add logging support to local transport used for proxy
2 parents 5c71b26 + 86aee1c commit 4ed3d4d

File tree

3 files changed

+79
-18
lines changed

3 files changed

+79
-18
lines changed

src/lib/types.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,8 @@ export interface OAuthCallbackServerOptions {
3333
/** Event emitter to signal when auth code is received */
3434
events: EventEmitter
3535
}
36+
37+
/*
38+
* Connection status types used for logging (via local transport, in proxy mode)
39+
*/
40+
export type ConnStatus = 'connected' | 'connecting' | 'reconnecting' | 'authenticating' | 'error' | 'error_final'

src/lib/utils.ts

Lines changed: 63 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
33
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'
44
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
55
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
6+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
7+
import { LoggingLevel } from '@modelcontextprotocol/sdk/types.js'
8+
import { ConnStatus } from './types'
69

710
// Connection constants
811
export const REASON_AUTH_NEEDED = 'authentication-needed'
@@ -73,6 +76,29 @@ export function mcpProxy({ transportToClient, transportToServer }: { transportTo
7376
}
7477
}
7578

79+
/**
80+
* Extended StdioServerTransport class
81+
*/
82+
export class StdioServerTransportExt extends StdioServerTransport {
83+
/**
84+
* Send a log message through the transport
85+
* @param level The log level ('error' | 'debug' | 'info' | 'notice' | 'warning' | 'critical' | 'alert' | 'emergency')
86+
* @param data The data object to send (should be JSON serializable)
87+
* @param logger Optional logger name, defaults to 'mcp-remote'
88+
*/
89+
sendMessage(level: LoggingLevel, data: any, logger: string = 'mcp-remote') {
90+
return this.send({
91+
jsonrpc: '2.0',
92+
method: 'notifications/message',
93+
params: {
94+
level,
95+
logger,
96+
data,
97+
},
98+
})
99+
}
100+
}
101+
76102
/**
77103
* Type for the auth initialization function
78104
*/
@@ -99,9 +125,21 @@ export async function connectToRemoteServer(
99125
headers: Record<string, string>,
100126
authInitializer: AuthInitializer,
101127
transportStrategy: TransportStrategy = 'http-first',
128+
localTransport: StdioServerTransportExt | null = null,
102129
recursionReasons: Set<string> = new Set(),
103130
): Promise<Transport> {
104-
log(`[${pid}] Connecting to remote server: ${serverUrl}`)
131+
const _log = (level: LoggingLevel, message: any, status: ConnStatus) => {
132+
// If localTransport is provided (proxy mode), send the message to it
133+
if (localTransport) {
134+
localTransport.sendMessage(level, {
135+
status,
136+
message,
137+
})
138+
}
139+
log(message)
140+
}
141+
142+
_log('info', `[${pid}] Connecting to remote server: ${serverUrl}`, 'connecting')
105143
const url = new URL(serverUrl)
106144

107145
// Create transport with eventSourceInit to pass Authorization header if present
@@ -121,7 +159,7 @@ export async function connectToRemoteServer(
121159
},
122160
}
123161

124-
log(`Using transport strategy: ${transportStrategy}`)
162+
_log('info', `Using transport strategy: ${transportStrategy}`, 'connecting')
125163
// Determine if we should attempt to fallback on error
126164
// Choose transport based on user strategy and recursion history
127165
const shouldAttemptFallback = transportStrategy === 'http-first' || transportStrategy === 'sse-first'
@@ -154,7 +192,7 @@ export async function connectToRemoteServer(
154192
await testClient.connect(testTransport)
155193
}
156194
}
157-
log(`Connected to remote server using ${transport.constructor.name}`)
195+
_log('info', `Connected to remote server using ${transport.constructor.name}`, 'connected')
158196

159197
return transport
160198
} catch (error) {
@@ -167,16 +205,16 @@ export async function connectToRemoteServer(
167205
error.message.includes('404') ||
168206
error.message.includes('Not Found'))
169207
) {
170-
log(`Received error: ${error.message}`)
208+
_log('error', `Received error: ${error.message}`, 'error')
171209

172210
// If we've already tried falling back once, throw an error
173211
if (recursionReasons.has(REASON_TRANSPORT_FALLBACK)) {
174212
const errorMessage = `Already attempted transport fallback. Giving up.`
175-
log(errorMessage)
213+
_log('error', errorMessage, 'error_final')
176214
throw new Error(errorMessage)
177215
}
178216

179-
log(`Recursively reconnecting for reason: ${REASON_TRANSPORT_FALLBACK}`)
217+
_log('info', `Recursively reconnecting for reason: ${REASON_TRANSPORT_FALLBACK}`, 'reconnecting')
180218

181219
// Add to recursion reasons set
182220
recursionReasons.add(REASON_TRANSPORT_FALLBACK)
@@ -189,45 +227,55 @@ export async function connectToRemoteServer(
189227
headers,
190228
authInitializer,
191229
sseTransport ? 'http-only' : 'sse-only',
230+
localTransport,
192231
recursionReasons,
193232
)
194233
} else if (error instanceof UnauthorizedError || (error instanceof Error && error.message.includes('Unauthorized'))) {
195-
log('Authentication required. Initializing auth...')
234+
_log('info', 'Authentication required. Initializing auth...', 'authenticating')
196235

197236
// Initialize authentication on-demand
198237
const { waitForAuthCode, skipBrowserAuth } = await authInitializer()
199238

200239
if (skipBrowserAuth) {
201-
log('Authentication required but skipping browser auth - using shared auth')
240+
_log('info', 'Authentication required but skipping browser auth - using shared auth', 'authenticating')
202241
} else {
203-
log('Authentication required. Waiting for authorization...')
242+
_log('info', 'Authentication required. Waiting for authorization...', 'authenticating')
204243
}
205244

206245
// Wait for the authorization code from the callback
207246
const code = await waitForAuthCode()
208247

209248
try {
210-
log('Completing authorization...')
249+
_log('info', 'Completing authorization...', 'authenticating')
211250
await transport.finishAuth(code)
212251

213252
if (recursionReasons.has(REASON_AUTH_NEEDED)) {
214253
const errorMessage = `Already attempted reconnection for reason: ${REASON_AUTH_NEEDED}. Giving up.`
215-
log(errorMessage)
254+
_log('error', errorMessage, 'error_final')
216255
throw new Error(errorMessage)
217256
}
218257

219258
// Track this reason for recursion
220259
recursionReasons.add(REASON_AUTH_NEEDED)
221-
log(`Recursively reconnecting for reason: ${REASON_AUTH_NEEDED}`)
260+
_log('info', `Recursively reconnecting for reason: ${REASON_AUTH_NEEDED}`, 'reconnecting')
222261

223262
// Recursively call connectToRemoteServer with the updated recursion tracking
224-
return connectToRemoteServer(client, serverUrl, authProvider, headers, authInitializer, transportStrategy, recursionReasons)
263+
return connectToRemoteServer(
264+
client,
265+
serverUrl,
266+
authProvider,
267+
headers,
268+
authInitializer,
269+
transportStrategy,
270+
localTransport,
271+
recursionReasons,
272+
)
225273
} catch (authError) {
226-
log('Authorization error:', authError)
274+
_log('error', `Authorization error: ${authError}`, 'error_final')
227275
throw authError
228276
}
229277
} else {
230-
log('Connection error:', error)
278+
_log('error', `Connection error: ${error}`, 'error_final')
231279
throw error
232280
}
233281
}

src/proxy.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
*/
1111

1212
import { EventEmitter } from 'events'
13-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
13+
import { StdioServerTransportExt } from './lib/utils'
1414
import {
1515
connectToRemoteServer,
1616
log,
@@ -50,7 +50,7 @@ async function runProxy(
5050
})
5151

5252
// Create the STDIO transport for local connections
53-
const localTransport = new StdioServerTransport()
53+
const localTransport = new StdioServerTransportExt()
5454

5555
// Keep track of the server instance for cleanup
5656
let server: any = null
@@ -78,7 +78,15 @@ async function runProxy(
7878

7979
try {
8080
// Connect to remote server with lazy authentication
81-
const remoteTransport = await connectToRemoteServer(null, serverUrl, authProvider, headers, authInitializer, transportStrategy)
81+
const remoteTransport = await connectToRemoteServer(
82+
null,
83+
serverUrl,
84+
authProvider,
85+
headers,
86+
authInitializer,
87+
transportStrategy,
88+
localTransport,
89+
)
8290

8391
// Set up bidirectional proxy between local and remote transports
8492
mcpProxy({

0 commit comments

Comments
 (0)