5
5
6
6
import anyio
7
7
import httpx
8
+ from mcp .server import FastMCP
8
9
from mcp .types import (
9
10
LATEST_PROTOCOL_VERSION ,
10
11
CallToolResult ,
21
22
import pytest
22
23
from httpx_sse import aconnect_sse
23
24
24
- from mcp_grafana import mcp
25
+ from mcp_grafana . tools import add_tools
25
26
from mcp_grafana .middleware import run_sse_async_with_middleware
26
27
27
28
from pytest_httpserver import HTTPServer
28
29
29
30
31
+ @pytest .fixture
32
+ def mcp ():
33
+ mcp = FastMCP ("grafana" )
34
+ add_tools (mcp )
35
+ return mcp
36
+
37
+
30
38
class TestMiddleware :
31
39
"""
32
40
Test that our injected starlette middleware extracts headers and
@@ -36,7 +44,28 @@ class TestMiddleware:
36
44
"""
37
45
38
46
@pytest .mark .asyncio
39
- async def test_multiple_requests (self ):
47
+ async def test_no_headers_provided (self , mcp : FastMCP ):
48
+ """
49
+ Ensure that the middleware fails if no headers are provided.
50
+ """
51
+
52
+ # Monkeypatch the MCP server to use our middleware.
53
+ mcp .run_sse_async = MethodType (run_sse_async_with_middleware , mcp )
54
+ mcp .settings .host = "127.0.0.1"
55
+ mcp .settings .port = 9500
56
+ async with anyio .create_task_group () as tg :
57
+ tg .start_soon (mcp .run_sse_async , name = "mcp" )
58
+ # Wait for the server to start.
59
+ await asyncio .sleep (0.1 )
60
+ client = httpx .AsyncClient (
61
+ base_url = f"http://{ mcp .settings .host } :{ mcp .settings .port } "
62
+ )
63
+ resp = await client .get ("/sse" )
64
+ assert resp .status_code == httpx .codes .FORBIDDEN
65
+ tg .cancel_scope .cancel ()
66
+
67
+ @pytest .mark .asyncio
68
+ async def test_multiple_requests (self , mcp : FastMCP ):
40
69
"""
41
70
Ensure that the contextvars do not leak across requests.
42
71
0 commit comments