Skip to content

routes

Class info

🛈 DocStrings

setup_routes

setup_routes(server: ConfigInjectionServer) -> None

Set up API routes.

Source code in src/mcp_server_llmling/injection/routes.py
 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def setup_routes(server: ConfigInjectionServer) -> None:
    """Set up API routes."""

    @server.app.post(
        "/inject-config",
        response_model=ComponentResponse,
        tags=["config"],
        summary="Inject new configuration",
        description="Inject new configuration into the running server.",
        responses={
            200: {
                "description": "Configuration successfully injected",
                "content": {
                    "application/json": {
                        "example": {
                            "status": "success",
                            "message": "Config injected successfully",
                            "component_type": "resource",
                            "name": "example_resource",
                        }
                    }
                },
            },
            400: {"description": "Invalid configuration"},
        },
    )
    async def inject_config(config: dict[str, Any]) -> ComponentResponse:
        """Inject raw YAML configuration."""
        logger.debug("Received config: %s", config)
        try:
            # Update resources
            if resources := config.get("resources"):
                logger.debug("Processing resources: %s", resources)
                for name, resource in resources.items():
                    # Validate based on resource type
                    resource_type = resource.get("type")
                    logger.debug("Processing resource %s of type %s", name, resource_type)
                    validated: BaseResource
                    match resource_type:
                        case "path":
                            validated = PathResource.model_validate(resource)
                        case "text":
                            validated = TextResource.model_validate(resource)
                        case "cli":
                            validated = CLIResource.model_validate(resource)
                        case "source":
                            validated = SourceResource.model_validate(resource)
                        case "callable":
                            validated = CallableResource.model_validate(resource)
                        case _:
                            msg = f"Unknown resource type: {resource_type}"
                            raise ValueError(msg)  # noqa: TRY301

                    server.llm_server.runtime.register_resource(name, validated, replace=True)
                    logger.debug("Resource %s registered", name)

            # Update tools
            if tools := config.get("tools"):
                logger.debug("Processing tools: %s", tools)
                for name, tool in tools.items():
                    logger.debug("Processing tool: %s", name)
                    tool = ToolConfig.model_validate(tool)
                    server.llm_server.runtime._tool_registry.register(name, tool, replace=True)
                    logger.debug("Tool %s registered", name)
            msg = "Config injected successfully"
            name = "yaml_injection"
            result = SuccessResponse(message=msg, component_type="tool", name=name)
            logger.debug("Returning response: %s", result.model_dump())
        except Exception as e:
            logger.exception("Failed to inject config")
            raise HTTPException(status_code=400, detail=str(e)) from e
        else:
            return result

    @server.app.get(
        "/components",
        tags=["components"],
        summary="List all components",
        description="Get a list of all registered components grouped by type.",
        response_description="Dictionary containing arrays of component names",
        responses={
            200: {
                "description": "List of all components",
                "content": {
                    "application/json": {
                        "example": {
                            "resources": ["resource1", "resource2"],
                            "tools": ["tool1", "tool2"],
                            "prompts": ["prompt1", "prompt2"],
                        }
                    }
                },
            }
        },
    )
    async def list_components() -> dict[str, Sequence[str]]:
        """List all registered components."""
        return {
            "resources": server.llm_server.runtime.list_resource_names(),
            "tools": server.llm_server.runtime.list_tool_names(),
            "prompts": server.llm_server.runtime.list_prompt_names(),
        }

    # Resource endpoints
    @server.app.post(
        "/resources/{name}",
        response_model=ComponentResponse,
        tags=["components"],
        summary="Add or update resource",
        description="""
        Register a new resource or update an existing one.
        Supports various resource types including path, text, CLI, source,
        callable, and image.
        """,
        responses={
            200: {"description": "Resource successfully registered"},
            400: {"description": "Invalid resource configuration"},
        },
    )
    async def add_resource(name: str, resource: Resource) -> ComponentResponse:
        """Add or update a resource."""
        try:
            server.llm_server.runtime.register_resource(name, resource, replace=True)
            msg = f"Resource {name} registered"
            return SuccessResponse(message=msg, component_type="resource", name=name)
        except Exception as e:
            raise HTTPException(status_code=400, detail=str(e)) from e

    @server.app.get(
        "/resources",
        tags=["components"],
        summary="List all resources",
        description="Get a list of all registered resources with their full config.",
        responses={
            200: {
                "description": "Dictionary of resources",
                "content": {
                    "application/json": {
                        "example": {
                            "resource1": {
                                "type": "text",
                                "content": "Example content",
                            },
                            "resource2": {"type": "path", "path": "/example/path"},
                        }
                    }
                },
            }
        },
    )
    async def list_resources() -> dict[str, BaseResource]:
        """List all resources with their configuration."""
        return {
            name: server.llm_server.runtime._resource_registry[name]
            for name in server.llm_server.runtime.list_resource_names()
        }

    @server.app.delete(
        "/resources/{name}",
        response_model=ComponentResponse,
        tags=["components"],
        summary="Remove resource",
        description="Remove a registered resource by name.",
        responses={
            200: {"description": "Resource successfully removed"},
            404: {"description": "Resource not found"},
        },
    )
    async def remove_resource(name: str) -> ComponentResponse:
        """Remove a resource."""
        try:
            del server.llm_server.runtime._resource_registry[name]
            msg = f"Resource {name} removed"
            return SuccessResponse(message=msg, component_type="resource", name=name)
        except KeyError as e:
            raise HTTPException(status_code=404, detail=f"Resource {name} not found") from e

    # Tool endpoints
    @server.app.post(
        "/tools/{name}",
        response_model=ComponentResponse,
        tags=["components"],
        summary="Add or update tool",
        description="Register a new tool or update an existing one.",
        responses={
            200: {"description": "Tool successfully registered"},
            400: {"description": "Invalid tool configuration"},
        },
    )
    async def add_tool(name: str, tool: ToolConfig) -> ComponentResponse:
        """Add or update a tool."""
        try:
            server.llm_server.runtime._tool_registry.register(name, tool, replace=True)
            msg = f"Tool {name} registered"
            return SuccessResponse(message=msg, component_type="tool", name=name)
        except Exception as e:
            raise HTTPException(status_code=400, detail=str(e)) from e

    @server.app.get(
        "/tools",
        tags=["components"],
        summary="List all tools",
        description="Get a list of all registered tools with their OpenAPI schemas.",
        responses={
            200: {
                "description": "Dictionary of tools with their schemas",
                "content": {
                    "application/json": {
                        "example": {
                            "tool1": {
                                "name": "tool1",
                                "description": "Example tool",
                                "parameters": {
                                    "type": "object",
                                    "properties": {},
                                },
                            }
                        }
                    }
                },
            },
            500: {"description": "Failed to get tool schemas"},
        },
    )
    async def list_tools() -> dict[str, OpenAIFunctionTool]:
        """List all tools with their OpenAPI schemas."""
        try:
            return {
                name: tool.get_schema() for name, tool in server.llm_server.runtime.tools.items()
            }
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Failed to get tool schemas: {e}") from e

    @server.app.delete(
        "/tools/{name}",
        response_model=ComponentResponse,
        tags=["components"],
        summary="Remove tool",
        description="Remove a registered tool by name.",
        responses={
            200: {"description": "Tool successfully removed"},
            404: {"description": "Tool not found"},
        },
    )
    async def remove_tool(name: str) -> ComponentResponse:
        """Remove a tool."""
        try:
            del server.llm_server.runtime._tool_registry[name]
            msg = f"Tool {name} removed"
            return SuccessResponse(message=msg, component_type="tool", name=name)
        except KeyError as e:
            raise HTTPException(status_code=404, detail=f"Tool {name} not found") from e

    # Bulk update endpoint
    @server.app.post(
        "/bulk-update",
        response_model=BulkUpdateResponse,
        tags=["config"],
        summary="Bulk update components",
        description="""
        Update multiple components in a single request.

        This endpoint allows you to register multiple resources and tools at once.
        Failed operations will be reported in the response but won't affect others.
        """,
        responses={
            200: {
                "description": "Bulk update results",
                "content": {
                    "application/json": {
                        "example": {
                            "results": [
                                {
                                    "status": "success",
                                    "message": "Resource registered",
                                    "component_type": "resource",
                                    "name": "example",
                                }
                            ],
                            "summary": {"success": 1, "error": 0},
                        }
                    }
                },
            },
        },
    )
    async def bulk_update(request: ConfigUpdateRequest) -> BulkUpdateResponse:
        """Update multiple components at once."""
        responses: list[ComponentResponse] = []
        summary = {"success": 0, "error": 0}
        res: ComponentResponse
        if request.resources:
            for name, resource in request.resources.items():
                try:
                    server.llm_server.runtime.register_resource(
                        name, resource, replace=request.replace_existing
                    )
                    msg = f"Resource {name} registered"
                    res = SuccessResponse(message=msg, component_type="resource", name=name)
                    responses.append(res)
                    summary["success"] += 1
                except Exception as e:  # noqa: BLE001
                    er = ErrorResponse(message=str(e), component_type="resource", name=name)
                    responses.append(er)
                    summary["error"] += 1

        if request.tools:
            for name, tool in request.tools.items():
                try:
                    server.llm_server.runtime._tool_registry.register(
                        name, tool, replace=request.replace_existing
                    )
                    msg = f"Tool {name} registered"
                    res = SuccessResponse(message=msg, component_type="tool", name=name)
                    responses.append(res)
                    summary["success"] += 1
                except Exception as e:  # noqa: BLE001
                    er = ErrorResponse(message=str(e), component_type="tool", name=name)
                    responses.append(er)
                    summary["error"] += 1

        return BulkUpdateResponse(results=responses, summary=summary)

    @server.app.websocket("/ws")
    async def websocket_endpoint(websocket: WebSocket) -> None:
        """Handle WebSocket connections."""
        await websocket.accept()
        logger.debug("WebSocket connection accepted")

        try:
            # First message handling
            raw_data = await websocket.receive_json()
            logger.debug("Received WebSocket data: %s", raw_data)

            message = WebSocketMessage.model_validate(raw_data)
            logger.debug("Validated message: %s", message)

            match message.type:
                case "update":
                    try:
                        logger.debug("Processing update request")
                        # Don't validate data again, it's already a dict
                        update_result = await bulk_update(
                            ConfigUpdateRequest.model_validate(message.data)
                        )
                        response = WebSocketResponse(
                            type="success",
                            data=update_result.results,
                            request_id=message.request_id,
                            message="Components updated successfully",
                        )
                        logger.debug("Update successful")
                    except Exception as e:
                        logger.exception("Update processing failed")
                        response = WebSocketResponse(
                            type="error",
                            data={},
                            message=str(e),
                            request_id=message.request_id,
                        )

                case "query":
                    logger.debug("Processing query request")
                    components = {
                        "resources": server.llm_server.runtime.list_resource_names(),
                        "tools": server.llm_server.runtime.list_tool_names(),
                        "prompts": server.llm_server.runtime.list_prompt_names(),
                    }
                    response = WebSocketResponse(
                        type="success",
                        data=components,
                        request_id=message.request_id,
                    )
                    logger.debug("Query successful")

                case _:
                    logger.error("Unknown message type: %s", message.type)
                    response = WebSocketResponse(
                        type="error",
                        data={},
                        message=f"Unknown message type: {message.type}",
                        request_id=message.request_id,
                    )

            logger.debug("Sending response: %s", response.model_dump())
            await websocket.send_json(response.model_dump())

        except WebSocketDisconnect:
            logger.debug("WebSocket client disconnected")
        except Exception as e:
            logger.exception("WebSocket operation failed")
            try:
                error_response = WebSocketResponse(
                    type="error",
                    data={},
                    message=str(e),
                    request_id=getattr(message, "request_id", None),
                ).model_dump()
                await websocket.send_json(error_response)
            except Exception:
                logger.exception("Failed to send error response")

    @server.app.post(
        "/dependencies/install",
        response_model=PackageInstallResponse,
        tags=["dependencies"],
        summary="Install package dependency",
        description="""
        Install a Python package using pip. The package spec can include version
        constraints (e.g. "requests>=2.28.0").
        """,
        responses={
            200: {"description": "Package installed successfully"},
            400: {"description": "Invalid package specification"},
            500: {"description": "Installation failed"},
        },
    )
    async def install_dependency(
        request: PackageInstallRequest,
    ) -> PackageInstallResponse:
        """Install a Python package dependency."""
        try:
            msg = await server.llm_server.runtime.install_package(request.package)
            return PackageInstallResponse(
                status="success",
                message=msg,
                package=request.package,
            )
        except Exception as e:
            logger.exception("Package installation failed")
            return PackageInstallResponse(
                status="error",
                message=f"Installation failed: {e}",
                package=request.package,
            )

    @server.app.post(
        "/tools/code/{name}",
        response_model=ComponentResponse,
        tags=["components"],
        summary="Register tool from code",
        description="""
        Register a new tool from Python code. The code should define a function
        that will be used as the tool implementation.
        """,
        responses={
            200: {"description": "Tool registered successfully"},
            400: {"description": "Invalid code or registration failed"},
        },
    )
    async def register_code_tool(request: CodeToolRequest) -> ComponentResponse:
        """Register a new tool from Python code."""
        try:
            msg = await server.llm_server.runtime.register_code_tool(
                name=request.name,
                code=request.code,
                description=request.description,
            )
            return SuccessResponse(
                message=msg,
                component_type="tool",
                name=request.name,
            )
        except Exception as e:  # noqa: BLE001
            return ErrorResponse(
                message=f"Failed to register tool: {e}",
                component_type="tool",
                name=request.name,
            )

    @server.app.post(
        "/tools/import/{name}",
        response_model=ComponentResponse,
        tags=["components"],
        summary="Register tool from import path",
        description="""
        Register a new tool by importing a function.

        The import path should be in the format 'module.submodule.function'.
        For example: 'webbrowser.open' or 'mypackage.tools.analyze'
        """,
        responses={
            200: {"description": "Tool successfully registered"},
            400: {"description": "Invalid import path or registration failed"},
        },
    )
    async def register_imported_tool(name: str, request: ImportToolRequest) -> ComponentResponse:
        """Register a tool from an import path."""
        try:
            await server.llm_server.runtime.register_tool(
                name=name,
                function=request.import_path,
                description=request.description,
            )
            msg = f"Tool {name} registered from {request.import_path}"
            return SuccessResponse(message=msg, component_type="tool", name=name)
        except Exception as e:
            logger.exception("Failed to register imported tool")
            raise HTTPException(status_code=400, detail=str(e)) from e