File size: 9,342 Bytes
1cf571b
 
 
 
 
 
 
 
 
 
 
4d76348
1cf571b
 
 
 
474f6dc
1cf571b
1ba61d9
1cf571b
 
 
 
 
 
 
 
 
 
 
 
474f6dc
 
 
1cf571b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082b2ad
 
 
 
 
 
 
 
 
1cf571b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082b2ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cf571b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d76348
1cf571b
 
1ba61d9
 
 
 
 
 
1cf571b
4d76348
 
 
 
1cf571b
4d76348
1cf571b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
FleetMind MCP Authentication Proxy
Captures API keys from initial SSE connections and injects them into tool requests.

This proxy sits between MCP clients and the FastMCP server, solving the
multi-tenant authentication problem by:
1. Capturing api_key from initial /sse?api_key=xxx connection
2. Storing api_key mapped to session_id
3. Injecting api_key into subsequent /messages/?session_id=xxx requests

Architecture:
  MCP Client -> Proxy (port 7860) -> FastMCP (port 7861)
"""

import asyncio
import logging
import os
from aiohttp import web, ClientSession, ClientTimeout
from aiohttp.client_exceptions import ClientConnectionResetError
from urllib.parse import urlencode, parse_qs, urlparse, urlunparse
import sys

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

# Proxy configuration
# On HuggingFace, PORT env var is set to 7860
PROXY_PORT = int(os.getenv("PORT", 7860))  # Public-facing port
FASTMCP_PORT = 7861  # Internal FastMCP server port (fixed)
FASTMCP_HOST = "localhost"

# Session storage: session_id -> api_key
session_api_keys = {}


async def proxy_handler(request):
    """
    Main proxy handler - forwards all requests to FastMCP server.
    Captures API keys from SSE connections and injects them into tool calls.
    """
    path = request.path
    query_params = dict(request.query)

    # Extract API key if present (initial SSE connection)
    api_key = query_params.get('api_key')
    session_id = query_params.get('session_id')

    # STEP 1: Capture API key from initial SSE connection
    if api_key and path == '/sse':
        logger.info(f"[AUTH] Captured API key from SSE connection: {api_key[:20]}...")
        # Store temporarily - will be linked to session when we see it
        session_api_keys['_pending_api_key'] = api_key

    # STEP 2: Link session_id to API key (from /messages requests)
    if session_id and path.startswith('/messages'):
        # Check if we have a stored API key for this session
        if session_id not in session_api_keys:
            # Link this session to the pending API key
            if '_pending_api_key' in session_api_keys:
                api_key_to_store = session_api_keys['_pending_api_key']
                session_api_keys[session_id] = api_key_to_store
                logger.info(f"[AUTH] Linked session {session_id[:12]}... to API key")

        # STEP 3: Inject API key into request for FastMCP
        stored_api_key = session_api_keys.get(session_id)
        if stored_api_key:
            query_params['api_key'] = stored_api_key
            logger.debug(f"[AUTH] Injected API key into request for session {session_id[:12]}...")

    # Build target URL for FastMCP server
    query_string = urlencode(query_params) if query_params else ""
    target_url = f"http://{FASTMCP_HOST}:{FASTMCP_PORT}{path}"
    if query_string:
        target_url += f"?{query_string}"

    # Forward request to FastMCP
    # For SSE connections: total=None disables overall timeout (keeps connection alive)
    # Still use socket timeouts for safety (sock_connect, sock_read)
    async with ClientSession(
        timeout=ClientTimeout(
            total=None,         # No total timeout for long-lived SSE connections
            sock_connect=30,    # 30 seconds for initial connection
            sock_read=300       # 5 minutes for individual socket reads
        )
    ) as session:
        try:
            # Copy headers
            headers = dict(request.headers)
            # Remove host header to avoid conflicts
            headers.pop('Host', None)

            # Forward request based on method
            if request.method == 'GET':
                async with session.get(target_url, headers=headers) as resp:
                    # For SSE, stream the response
                    if 'text/event-stream' in resp.content_type:
                        # Create streaming response for SSE
                        response = web.StreamResponse(
                            status=resp.status,
                            reason=resp.reason,
                            headers=dict(resp.headers)
                        )
                        await response.prepare(request)

                        # Background task to send keep-alive pings (prevents timeout)
                        async def send_keepalive():
                            try:
                                while True:
                                    await asyncio.sleep(30)  # Send ping every 30 seconds
                                    await response.write(b":\n\n")  # SSE comment (ignored by client)
                            except asyncio.CancelledError:
                                pass

                        keepalive_task = asyncio.create_task(send_keepalive())

                        try:
                            # Stream chunks from FastMCP to client
                            async for chunk in resp.content.iter_any():
                                await response.write(chunk)

                            await response.write_eof()
                        finally:
                            # Cancel keep-alive task when streaming completes
                            keepalive_task.cancel()
                            try:
                                await keepalive_task
                            except asyncio.CancelledError:
                                pass

                        return response
                    else:
                        # For regular responses, read entire body
                        body = await resp.read()
                        resp_headers = dict(resp.headers)
                        return web.Response(
                            body=body,
                            status=resp.status,
                            headers=resp_headers
                        )

            elif request.method == 'POST':
                body = await request.read()
                async with session.post(target_url, data=body, headers=headers) as resp:
                    resp_body = await resp.read()
                    # Don't pass content_type separately - it's already in headers
                    resp_headers = dict(resp.headers)
                    return web.Response(
                        body=resp_body,
                        status=resp.status,
                        headers=resp_headers
                    )

            else:
                # Forward other methods
                async with session.request(
                    request.method,
                    target_url,
                    data=await request.read(),
                    headers=headers
                ) as resp:
                    body = await resp.read()
                    return web.Response(
                        body=body,
                        status=resp.status,
                        headers=dict(resp.headers)
                    )

        except (ClientConnectionResetError, ConnectionResetError) as e:
            # Client disconnected - this is normal for SSE connections
            # Log at DEBUG level to reduce noise
            logger.debug(f"[SSE] Client disconnected: {e}")
            return web.Response(text="Client disconnected", status=499)

        except Exception as e:
            import traceback
            error_details = traceback.format_exc()
            logger.error(f"[ERROR] Proxy error: {type(e).__name__}: {e}")
            logger.error(f"[ERROR] Traceback:\n{error_details}")
            return web.Response(
                text=f"Proxy error: {type(e).__name__}: {str(e)}",
                status=502
            )


async def health_check(request):
    """Health check endpoint"""
    return web.Response(text="FleetMind Proxy OK", status=200)


def create_app():
    """Create and configure the proxy application"""
    app = web.Application()

    # Health check endpoint
    app.router.add_get('/health', health_check)

    # Proxy all other requests
    app.router.add_route('*', '/{path:.*}', proxy_handler)

    return app


async def main():
    """Start the proxy server"""
    print("\n" + "=" * 70)
    print("FleetMind MCP Authentication Proxy")
    print("=" * 70)
    print(f"Proxy listening on: http://0.0.0.0:{PROXY_PORT}")
    print(f"Forwarding to FastMCP: http://{FASTMCP_HOST}:{FASTMCP_PORT}")
    print("=" * 70)
    print("[OK] Multi-tenant authentication enabled")
    print("[OK] API keys captured from SSE connections")
    print("[OK] Sessions automatically linked to API keys")
    print("=" * 70 + "\n")

    app = create_app()
    runner = web.AppRunner(app)
    await runner.setup()

    site = web.TCPSite(runner, '0.0.0.0', PROXY_PORT)
    await site.start()

    logger.info(f"[OK] Proxy server started on port {PROXY_PORT}")
    logger.info(f"[OK] Forwarding to FastMCP on {FASTMCP_HOST}:{FASTMCP_PORT}")

    # Keep running
    try:
        await asyncio.Event().wait()
    except KeyboardInterrupt:
        logger.info("Shutting down proxy server...")
        await runner.cleanup()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nProxy server stopped.")
        sys.exit(0)