{"record":{"id":"836f8f6a02a0ba35","repo":"PrefectHQ/fastmcp","slug":"failed-to-resolve-dependency-parameter-for-fn","errorCode":null,"errorMessage":"Failed to resolve dependency '{parameter}' for {fn_name}","messagePattern":"Failed to resolve dependency '(.+?)' for (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"fastmcp_slim/fastmcp/server/dependencies.py","lineNumber":813,"sourceCode":"                # the same value the function receives for it.\n                with frame_scope(fn, arguments) as frame:\n                    resolved: dict[str, Any] = {}\n\n                    for parameter in dependency_params:\n                        # Resolve the dependency. The frame returns an\n                        # explicitly provided argument as-is.\n                        try:\n                            resolved[parameter] = await frame.resolve(parameter)\n                        except (FastMCPError, CycleError):\n                            # Let FastMCPError subclasses (ToolError,\n                            # ResourceError, etc.) propagate unchanged so they\n                            # can be handled appropriately. CycleError already\n                            # names the cyclic reference path, so wrapping it\n                            # would only hide that.\n                            raise\n                        except Exception as error:\n                            fn_name = getattr(fn, \"__name__\", repr(fn))\n                            raise RuntimeError(\n                                f\"Failed to resolve dependency '{parameter}' \"\n                                f\"for {fn_name}\"\n                            ) from error\n\n                    # Merge resolved dependencies with provided arguments\n                    final_arguments = {**arguments, **resolved}\n\n                    yield final_arguments\n            finally:\n                _Depends.stack.reset(stack_token)\n    finally:\n        _Depends.cache.reset(cache_token)\n\n\n@asynccontextmanager\nasync def resolve_dependencies(\n    fn: Callable[..., Any], arguments: dict[str, Any]\n) -> AsyncGenerator[dict[str, Any], None]:","sourceCodeStart":795,"sourceCodeEnd":831,"githubUrl":"https://github.com/PrefectHQ/fastmcp/blob/1f021142978e0861cd910c8df4e8074bc7cf3978/fastmcp_slim/fastmcp/server/dependencies.py#L795-L831","documentation":"FastMCP resolves function parameters marked as dependencies (e.g. Context, Progress, AccessToken providers) before invoking a tool, resource, or prompt. When a dependency's factory raises any exception other than a dependency CycleError (which is re-raised verbatim so the cycle path stays visible), it is wrapped in a RuntimeError naming the parameter and the function, with the original error attached via `raise ... from error`. The wrapper exists to tell you exactly which parameter on which function could not be resolved.","triggerScenarios":"Calling resolve_dependencies on a function whose annotated dependency parameter raises during resolution — e.g. a Progress or AccessToken provider entered outside a server context, a user-supplied dependency factory raising, or a type annotation that maps to no known provider and its factory throws.","commonSituations":"A tool with a `progress: Progress` parameter invoked via the client (not inside a request context); a custom dependency class whose __aenter__ raises; renaming a function so an internal registry lookup fails; typos in dependency type annotations.","solutions":["Read the chained `from error` cause in the traceback (the `__cause__`) — the RuntimeError only names the parameter; the real failure is the inner exception","Check the annotated type of the named parameter on fn_name; ensure it maps to a registered dependency provider","If the parameter needs a request context (Context/Progress/AccessToken), only invoke the function through the FastMCP server request path, not directly in a background thread","If it is a custom dependency, fix the exception raised inside its factory/__aenter__"],"exampleFix":"// before\ndef my_tool(progress: Progress, db: NotADependency) -> str: ...\n// after\nfrom fastmcp.server.dependencies import Progress\ndef my_tool(ctx: Context, progress: Progress) -> str: ...","handlingStrategy":"try-catch","validationCode":"import inspect, fastmcp.server.dependencies as deps\nfor name, ann in inspect.signature(fn).parameters.items():\n    if ann.annotation in deps._known_dependency_types():\n        print(f'{name} resolves via built-in provider')","typeGuard":"def has_dependency_params(fn) -> bool:\n    return any(\n        isinstance(p.annotation, type) and issubclass(p.annotation, Dependent)\n        for p in inspect.signature(fn).parameters.values()\n    )","tryCatchPattern":"try:\n    args = resolve_dependencies(fn, arguments)\nexcept RuntimeError as e:\n    logger.error(f'{e.__cause__!r}')  # real cause is chained\n    raise","preventionTips":["Always inspect `e.__cause__` when this RuntimeError appears — the wrapper hides the root error","Keep dependency annotations to types FastMCP knows (Context, Progress, AccessToken, custom registered providers)","Never call tool functions directly in production paths; invoke them through the server/client","Test dependency-injected functions via the in-memory Client"],"tags":["dependency-injection","runtime","fastmcp"],"backgroundTag":"dependency-resolution-failed","analyzedSha":"1f021142978e0861cd910c8df4e8074bc7cf3978","analyzedAt":"2026-08-29T14:31:16.082Z","schemaVersion":2},"datasetVersion":"2026-08-29T17:17:51.833Z"}