Coverage for /Users/antonigmitruk/golf/src/golf/utilities/context.py: 0%

12 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-08-16 18:46 +0200

1"""Context utilities for Golf MCP tools. 

2 

3This module provides utilities to access the current FastMCP Context 

4from within Golf tool functions. 

5""" 

6 

7from typing import TYPE_CHECKING 

8 

9if TYPE_CHECKING: 

10 from fastmcp.server.context import Context 

11 

12 

13def get_current_context() -> "Context": 

14 """Get the current FastMCP Context. 

15 

16 This function retrieves the current FastMCP Context that was injected 

17 into the tool function. It works by importing the FastMCP context 

18 utilities at runtime. 

19 

20 Returns: 

21 The current FastMCP Context instance 

22 

23 Raises: 

24 RuntimeError: If called outside of an MCP request context 

25 ImportError: If FastMCP is not available 

26 

27 Example: 

28 ```python 

29 from golf.utilities import get_current_context 

30 

31 async def my_tool(data: str): 

32 ctx = get_current_context() 

33 await ctx.info(f"Processing: {data}") 

34 return "done" 

35 ``` 

36 """ 

37 try: 

38 # Import FastMCP context utilities at runtime 

39 from fastmcp.server.context import _current_context 

40 

41 # Get the current context from the context variable 

42 context = _current_context.get(None) 

43 

44 if context is None: 

45 raise RuntimeError( 

46 "No FastMCP Context available. This function must be called " 

47 "from within an MCP tool function that has context injection enabled." 

48 ) 

49 

50 return context 

51 

52 except ImportError as e: 

53 raise ImportError("FastMCP is not available. Please ensure fastmcp>=2.11.0 is installed.") from e