{"record":{"id":"d7082cc4ccf65c49","repo":"microsoft/semantic-kernel","slug":"request-context-is-required-for-sampling-function","errorCode":null,"errorMessage":"Request context is required for sampling function.","messagePattern":"Request context is required for sampling function\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/samples/demos/mcp_server/mcp_server_with_sampling.py","lineNumber":71,"sourceCode":"\nInclude the output in raw markdown.\n\"\"\"\n\n\n@kernel_function(\n    name=\"run_prompt\",\n    description=\"This run the prompts for a full set of release notes based on the PR messages given.\",\n)\nasync def sampling_function(\n    messages: Annotated[str, \"The list of PR messages, as a string with newlines\"],\n    temperature: float = 0.0,\n    max_tokens: int = 1000,\n    # The include_in_function_choices is set to False, so it won't be included in the function choices,\n    # but it will get the server instance from the MCPPlugin that consumes this server.\n    server: Annotated[Server | None, \"The server session\", {\"include_in_function_choices\": False}] = None,\n) -> str:\n    if not server:\n        raise ValueError(\"Request context is required for sampling function.\")\n    sampling_response = await server.request_context.session.create_message(\n        messages=[\n            types.SamplingMessage(role=\"user\", content=types.TextContent(type=\"text\", text=messages)),\n        ],\n        max_tokens=max_tokens,\n        temperature=temperature,\n        model_preferences=types.ModelPreferences(\n            hints=[types.ModelHint(name=\"gpt-4o-mini\")],\n        ),\n    )\n    logger.info(f\"Sampling response: {sampling_response}\")\n    return sampling_response.content.text\n\n\ndef run() -> None:\n    \"\"\"Run the MCP server with the release notes prompt template.\"\"\"\n    kernel = Kernel()\n    kernel.add_function(\"release_notes\", sampling_function)","sourceCodeStart":53,"sourceCodeEnd":89,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/samples/demos/mcp_server/mcp_server_with_sampling.py#L53-L89","documentation":"Raised by the MCP server sampling_function when the injected Server session is None. The function relies on Semantic Kernel's MCPPlugin to inject the live server session via the 'server' parameter (marked include_in_function_choices=False). If the function is invoked outside that injection path, server is None and sampling cannot reach request_context.session.create_message.","triggerScenarios":"Calling sampling_function() directly/standalone without going through the kernel function pipeline that injects the server; the MCPPlugin failed to bind the server to the parameter; the server is not actually running/registered.","commonSituations":"See trigger scenarios.","solutions":["Invoke sampling_function only through the kernel/MCP plugin so the Server is injected.","Ensure the MCP server hosting this tool is registered with MCPPlugin before the function is called.","Verify the 'server' parameter annotation and metadata match what MCPPlugin expects for injection.","Do not unit-test by calling the function with server=None; pass a mock Server with a request_context.session."],"exampleFix":"// before\nawait sampling_function(messages='pr list')  # server defaults to None\n\n// after\n# invoke through the kernel so MCPPlugin injects the server\nresult = await kernel.invoke(plugin_name='MCPPlugin', function_name='run_prompt', messages='pr list')","handlingStrategy":"validation","validationCode":"if server is None:\n    raise ValueError('sampling_function must be invoked through the kernel/MCPPlugin so the server is injected')\nsampling_response = await server.request_context.session.create_message(...)","typeGuard":"def has_server_session(server) -> bool:\n    return (\n        server is not None\n        and getattr(getattr(server, 'request_context', None), 'session', None) is not None\n    )","tryCatchPattern":null,"preventionTips":["Only call sampling_function via kernel.invoke so MCPPlugin injects the server.","Register the MCP server with MCPPlugin before invoking tools.","In tests, inject a mock server with a request_context.session."],"tags":["mcp","sampling","dependency-injection","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}