Skip to content

Commit 5f37e46

Browse files
Python: add support for prompts and sample (microsoft#11508)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> Allow a list of prompts to be added and exposed with the MCP server setup. This uses the built-in rendering types (all of them) to be used and exposed as prompts. Closes: microsoft#11143 ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [x] The code builds clean without any errors or warnings - [x] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [x] All unit tests pass, and I have added new tests where possible - [x] I didn't break anyone 😄
1 parent 779f87f commit 5f37e46

16 files changed

Lines changed: 829 additions & 136 deletions

‎python/samples/concepts/mcp/README.md‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,22 @@ The code shown works the same for a Sse server, only then a MCPSsePlugin needs t
2020

2121
The reverse, using Semantic Kernel as a server, can be found in the [demos/sk_mcp_server](../../demos/sk_mcp_server/) folder.
2222

23-
## Running the sample
23+
## Running the samples
2424

25-
1. Make sure you have the [Node.js](https://nodejs.org/en/download/) installed.
26-
2. Make sure you have the [npx](https://docs.npmjs.com/cli/v8/commands/npx) available in PATH.
27-
3. The Github MCP Server uses a Github Personal Access Token (PAT) to authenticate, see [the documentation](https://github.com/modelcontextprotocol/servers/tree/main/src/github) on how to create one.
28-
4. Install Semantic Kernel with the mcp extra:
25+
1. Depending on the sample you want to run:
26+
1. [Docker](https://www.docker.com/products/docker-desktop/) installed, for the samples that use the Github MCP server.
27+
1. [uv](https://docs.astral.sh/uv/getting-started/installation/) installed, for the samples that use the local MCP server.
28+
2. The Github MCP Server uses a Github Personal Access Token (PAT) to authenticate, see [the documentation](https://github.com/modelcontextprotocol/servers/tree/main/src/github) on how to create one.
29+
1. Check the comment at the start of the sample you want to run, for the appropriate environment variables to set.
30+
1. Install Semantic Kernel with the mcp extra:
2931

3032
```bash
3133
pip install semantic-kernel[mcp]
3234
```
3335

34-
5. Run the sample:
36+
4. Run any of the samples:
3537

3638
```bash
3739
cd python/samples/concepts/mcp
38-
python mcp_as_plugin.py
39-
```
40-
41-
or:
42-
43-
```bash
44-
cd python/samples/concepts/mcp
45-
python agent_with_mcp_plugin.py
40+
python <name>.py
4641
```

‎python/samples/concepts/mcp/agent_with_mcp_plugin.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright (c) Microsoft. All rights reserved.
22

33
import asyncio
4+
import os
45

56
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
67
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
@@ -9,8 +10,13 @@
910
"""
1011
The following sample demonstrates how to create a chat completion agent that
1112
answers questions about Github using a Semantic Kernel Plugin from a MCP server.
12-
The Chat Completion Service is passed directly via the ChatCompletionAgent constructor.
13-
Additionally, the plugin is supplied via the constructor.
13+
14+
It uses the Azure OpenAI service to create a agent, so make sure to
15+
set the required environment variables for the Azure AI Foundry service:
16+
- AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
17+
- Optionally: AZURE_OPENAI_API_KEY
18+
If this is not set, it will try to use DefaultAzureCredential.
19+
1420
"""
1521

1622

@@ -27,8 +33,9 @@ async def main():
2733
async with MCPStdioPlugin(
2834
name="Github",
2935
description="Github Plugin",
30-
command="npx",
31-
args=["-y", "@modelcontextprotocol/server-github"],
36+
command="docker",
37+
args=["run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "ghcr.io/github/github-mcp-server"],
38+
env={"GITHUB_PERSONAL_ACCESS_TOKEN": os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN")},
3239
) as github_plugin:
3340
agent = ChatCompletionAgent(
3441
service=AzureChatCompletion(),
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import logging
5+
import os
6+
from pathlib import Path
7+
8+
from semantic_kernel.agents import ChatCompletionAgent
9+
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
10+
from semantic_kernel.connectors.mcp import MCPStdioPlugin
11+
12+
# set this lower or higher depending on your needs
13+
logging.basicConfig(level=logging.INFO)
14+
logger = logging.getLogger(__name__)
15+
16+
"""
17+
The following sample demonstrates how to use a MCP Server that requires sampling
18+
to generate release notes from a list of issues.
19+
20+
It uses the OpenAI service to create a agent, so make sure to
21+
set the required environment variables for the Azure AI Foundry service:
22+
- OPENAI_API_KEY
23+
- OPENAI_CHAT_MODEL_ID
24+
"""
25+
26+
PR_MESSAGES = """* Python: Add ChatCompletionAgent integration tests by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11430
27+
* Python: Update Doc Gen demo based on latest agent invocation api pattern by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11426
28+
* Python: Update Python min version in README by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11428
29+
* Python: Fix `TypeError` when required is missing in MCP tool’s inputSchema by @KanchiShimono in https://github.com/microsoft/semantic-kernel/pull/11458
30+
* Python: Update chromadb requirement from <0.7,>=0.5 to >=0.5,<1.1 in /python by @dependabot in https://github.com/microsoft/semantic-kernel/pull/11420
31+
* Python: Bump google-cloud-aiplatform from 1.86.0 to 1.87.0 in /python by @dependabot in https://github.com/microsoft/semantic-kernel/pull/11423
32+
* Python: Support Auto Function Invocation Filter for AzureAIAgent and OpenAIAssistantAgent by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11460
33+
* Python: Improve agent integration tests by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11475
34+
* Python: Allow Kernel Functions from Prompt for image and audio content by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11403
35+
* Python: Introducing SK as a MCP Server by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11362
36+
* Python: sample using GitHub MCP Server and Azure AI Agent by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11465
37+
* Python: allow settings to be created directly by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11468
38+
* Python: Bug fix for azure ai agent truncate strategy. Add sample. by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11503
39+
* Python: small code improvements in code of call automation sample by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11477
40+
* Added missing import asyncio to agent with plugin python by @sphenry in https://github.com/microsoft/semantic-kernel/pull/11472
41+
* Python: version updated to 1.28.0 by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11504"""
42+
43+
44+
async def main():
45+
# 1. Create the agent
46+
async with MCPStdioPlugin(
47+
name="ReleaseNotes",
48+
description="SK Release Notes Plugin",
49+
command="uv",
50+
args=[
51+
f"--directory={str(Path(os.path.dirname(__file__)).parent.parent.joinpath('demos', 'sk_mcp_server'))}",
52+
"run",
53+
"mcp_server_with_sampling.py",
54+
],
55+
) as plugin:
56+
agent = ChatCompletionAgent(
57+
service=OpenAIChatCompletion(),
58+
name="IssueAgent",
59+
instructions="For the messages supplied, call the release_notes_prompt function to get the broader "
60+
"prompt, then call the run_prompt function to get the final output, return that without any other text."
61+
"Do not add any other text to the output, or rewrite the output from run_prompt.",
62+
plugins=[plugin],
63+
)
64+
65+
print(f"# Task: {PR_MESSAGES}")
66+
# 3. Invoke the agent for a response
67+
response = await agent.get_response(messages=PR_MESSAGES)
68+
print(str(response))
69+
70+
# 4. Cleanup: Clear the thread
71+
await response.thread.delete()
72+
73+
"""
74+
# Task: * Python: Add ChatCompletionAgent integration tests by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11430
75+
* Python: Update Doc Gen demo based on latest agent invocation api pattern by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11426
76+
* Python: Update Python min version in README by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11428
77+
* Python: Fix `TypeError` when required is missing in MCP tool’s inputSchema by @KanchiShimono in https://github.com/microsoft/semantic-kernel/pull/11458
78+
* Python: Update chromadb requirement from <0.7,>=0.5 to >=0.5,<1.1 in /python by @dependabot in https://github.com/microsoft/semantic-kernel/pull/11420
79+
* Python: Bump google-cloud-aiplatform from 1.86.0 to 1.87.0 in /python by @dependabot in https://github.com/microsoft/semantic-kernel/pull/11423
80+
* Python: Support Auto Function Invocation Filter for AzureAIAgent and OpenAIAssistantAgent by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11460
81+
* Python: Improve agent integration tests by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11475
82+
* Python: Allow Kernel Functions from Prompt for image and audio content by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11403
83+
* Python: Introducing SK as a MCP Server by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11362
84+
* Python: sample using GitHub MCP Server and Azure AI Agent by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11465
85+
* Python: allow settings to be created directly by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11468
86+
* Python: Bug fix for azure ai agent truncate strategy. Add sample. by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11503
87+
* Python: small code improvements in code of call automation sample by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11477
88+
* Added missing import asyncio to agent with plugin python by @sphenry in https://github.com/microsoft/semantic-kernel/pull/11472
89+
* Python: version updated to 1.28.0 by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11504
90+
91+
Here’s a summary of the recent changes and contributions made to the Microsoft Semantic Kernel repository:
92+
93+
1. **Integration Tests**:
94+
- Added integration tests for `ChatCompletionAgent` by @moonbox3 ([PR #11430](https://github.com/microsoft/semantic-kernel/pull/11430)).
95+
- Improved agent integration tests by @moonbox3 ([PR #11475](https://github.com/microsoft/semantic-kernel/pull/11475)).
96+
97+
2. **Documentation and Demos**:
98+
- Updated the Doc Gen demo to align with the latest agent invocation API pattern by @moonbox3 ([PR #11426](https://github.com/microsoft/semantic-kernel/pull/11426)).
99+
- Small code improvements made in the code of the call automation sample by @eavanvalkenburg ([PR #11477](https://github.com/microsoft/semantic-kernel/pull/11477)).
100+
101+
3. **Version Updates**:
102+
- Updated the minimum Python version in the README by @moonbox3 ([PR #11428](https://github.com/microsoft/semantic-kernel/pull/11428)).
103+
- Updated `chromadb` requirement to allow versions >=0.5 and <1.1 by @dependabot ([PR #11420](https://github.com/microsoft/semantic-kernel/pull/11420)).
104+
- Bumped `google-cloud-aiplatform` from 1.86.0 to 1.87.0 by @dependabot ([PR #11423](https://github.com/microsoft/semantic-kernel/pull/11423)).
105+
- Version updated to 1.28.0 by @eavanvalkenburg ([PR #11504](https://github.com/microsoft/semantic-kernel/pull/11504)).
106+
107+
4. **Bug Fixes**:
108+
- Fixed a `TypeError` in the MCP tool’s input schema when the required field is missing by @KanchiShimono ([PR #11458](https://github.com/microsoft/semantic-kernel/pull/11458)).
109+
- Bug fix for Azure AI agent truncate strategy with an added sample by @moonbox3 ([PR #11503](https://github.com/microsoft/semantic-kernel/pull/11503)).
110+
- Added a missing import for `asyncio` in the agent with plugin Python by @sphenry ([PR #11472](https://github.com/microsoft/semantic-kernel/pull/11472)).
111+
"""
112+
113+
114+
if __name__ == "__main__":
115+
asyncio.run(main())
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import os
5+
from pathlib import Path
6+
7+
from azure.identity.aio import DefaultAzureCredential
8+
9+
from semantic_kernel.agents import (
10+
AzureAIAgent,
11+
AzureAIAgentSettings,
12+
AzureAIAgentThread,
13+
)
14+
from semantic_kernel.connectors.mcp import MCPStdioPlugin
15+
from semantic_kernel.functions import KernelArguments
16+
17+
"""
18+
The following sample demonstrates how to create a chat completion agent that
19+
answers questions about Github using a Local Agent with two local MCP Servers.
20+
21+
It uses the Azure AI Foundry Agent service to create a agent, so make sure to
22+
set the required environment variables for the Azure AI Foundry service:
23+
- AZURE_AI_AGENT_PROJECT_CONNECTION_STRING
24+
- AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME
25+
"""
26+
27+
USER_INPUTS = [
28+
"list the latest 10 issues that have the label: triage and python and are open",
29+
"""generate release notes with this list:
30+
* Python: Add ChatCompletionAgent integration tests by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11430
31+
* Python: Update Doc Gen demo based on latest agent invocation api pattern by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11426
32+
* Python: Update Python min version in README by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11428
33+
* Python: Fix `TypeError` when required is missing in MCP tool’s inputSchema by @KanchiShimono in https://github.com/microsoft/semantic-kernel/pull/11458
34+
* Python: Update chromadb requirement from <0.7,>=0.5 to >=0.5,<1.1 in /python by @dependabot in https://github.com/microsoft/semantic-kernel/pull/11420
35+
* Python: Bump google-cloud-aiplatform from 1.86.0 to 1.87.0 in /python by @dependabot in https://github.com/microsoft/semantic-kernel/pull/11423
36+
* Python: Support Auto Function Invocation Filter for AzureAIAgent and OpenAIAssistantAgent by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11460
37+
* Python: Improve agent integration tests by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11475
38+
* Python: Allow Kernel Functions from Prompt for image and audio content by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11403
39+
* Python: Introducing SK as a MCP Server by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11362
40+
* Python: sample using GitHub MCP Server and Azure AI Agent by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11465
41+
* Python: allow settings to be created directly by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11468
42+
* Python: Bug fix for azure ai agent truncate strategy. Add sample. by @moonbox3 in https://github.com/microsoft/semantic-kernel/pull/11503
43+
* Python: small code improvements in code of call automation sample by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11477
44+
* Added missing import asyncio to agent with plugin python by @sphenry in https://github.com/microsoft/semantic-kernel/pull/11472
45+
* Python: version updated to 1.28.0 by @eavanvalkenburg in https://github.com/microsoft/semantic-kernel/pull/11504""",
46+
]
47+
48+
49+
async def main():
50+
# Load the MCP Servers as Plugins
51+
async with (
52+
# 1. Login to Azure and create a Azure AI Project Client
53+
DefaultAzureCredential() as creds,
54+
AzureAIAgent.create_client(credential=creds) as client,
55+
MCPStdioPlugin(
56+
name="Github",
57+
description="Github Plugin",
58+
command="docker",
59+
args=["run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "ghcr.io/github/github-mcp-server"],
60+
env={"GITHUB_PERSONAL_ACCESS_TOKEN": os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN")},
61+
) as github_plugin,
62+
MCPStdioPlugin(
63+
name="ReleaseNotes",
64+
description="SK Release Notes Plugin",
65+
command="uv",
66+
args=[
67+
f"--directory={str(Path(os.path.dirname(__file__)).parent.parent.joinpath('demos', 'sk_mcp_server'))}",
68+
"run",
69+
"mcp_server_with_prompts.py",
70+
],
71+
) as release_notes_plugin,
72+
):
73+
# 3. Create the agent, with the MCP plugin and the thread
74+
agent = AzureAIAgent(
75+
client=client,
76+
definition=await client.agents.create_agent(
77+
model=AzureAIAgentSettings().model_deployment_name,
78+
name="GithubAgent",
79+
instructions="You interact with the user to help them with the Microsoft semantic-kernel github "
80+
"project. You have dedicated tools for this, including one to write release notes, "
81+
"make sure to use that when needed. The repo is always semantic-kernel (aka SK) with owner Microsoft. "
82+
"and when doing lists, always return 5 items and sort descending by created or updated"
83+
"You are specialized in Python, so always include label, python, in addition to the other labels.",
84+
),
85+
plugins=[github_plugin, release_notes_plugin], # add the sample plugin to the agent
86+
)
87+
88+
# Create a thread to hold the conversation
89+
# If no thread is provided, a new thread will be
90+
# created and returned with the initial response
91+
thread: AzureAIAgentThread | None = None
92+
for user_input in USER_INPUTS:
93+
print(f"# User: {user_input}", end="\n\n")
94+
first_chunk = True
95+
async for response in agent.invoke_stream(
96+
messages=user_input,
97+
thread=thread,
98+
arguments=KernelArguments(owner="microsoft", repo="semantic-kernel"),
99+
):
100+
if first_chunk:
101+
print(f"# {response.name}: ", end="", flush=True)
102+
first_chunk = False
103+
print(response.content, end="", flush=True)
104+
thread = response.thread
105+
print()
106+
107+
# Cleanup: Clear the thread
108+
await thread.delete() if thread else None
109+
110+
111+
if __name__ == "__main__":
112+
asyncio.run(main())

‎python/samples/concepts/mcp/azure_ai_agent_with_mcp_plugin.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright (c) Microsoft. All rights reserved.
22

33
import asyncio
4+
import os
45

56
from azure.identity.aio import DefaultAzureCredential
67

@@ -10,6 +11,11 @@
1011
"""
1112
The following sample demonstrates how to create a AzureAIAgent that
1213
answers questions about Github using a Semantic Kernel Plugin from a MCP server.
14+
15+
It uses the Azure AI Foundry Agent service to create a agent, so make sure to
16+
set the required environment variables for the Azure AI Foundry service:
17+
- AZURE_AI_AGENT_PROJECT_CONNECTION_STRING
18+
- AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME
1319
"""
1420

1521

@@ -22,8 +28,9 @@ async def main():
2228
MCPStdioPlugin(
2329
name="github",
2430
description="Github Plugin",
25-
command="npx",
26-
args=["-y", "@modelcontextprotocol/server-github"],
31+
command="docker",
32+
args=["run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "ghcr.io/github/github-mcp-server"],
33+
env={"GITHUB_PERSONAL_ACCESS_TOKEN": os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN")},
2734
) as github_plugin,
2835
):
2936
# 3. Create the agent, with the MCP plugin and the thread

0 commit comments

Comments
 (0)