agentory 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentory-0.1.0/LICENSE +21 -0
- agentory-0.1.0/PKG-INFO +175 -0
- agentory-0.1.0/README.md +159 -0
- agentory-0.1.0/agentory/__init__.py +17 -0
- agentory-0.1.0/agentory/agent.py +115 -0
- agentory-0.1.0/agentory/mcp/__init__.py +3 -0
- agentory-0.1.0/agentory/mcp/schemas.py +70 -0
- agentory-0.1.0/agentory/mcp/server.py +238 -0
- agentory-0.1.0/agentory/skills/__init__.py +44 -0
- agentory-0.1.0/agentory/tools/__init__.py +5 -0
- agentory-0.1.0/agentory/tools/schema_builder.py +85 -0
- agentory-0.1.0/agentory/tools/tools.py +61 -0
- agentory-0.1.0/agentory/tools/views.py +80 -0
- agentory-0.1.0/agentory/views.py +10 -0
- agentory-0.1.0/agentory.egg-info/PKG-INFO +175 -0
- agentory-0.1.0/agentory.egg-info/SOURCES.txt +25 -0
- agentory-0.1.0/agentory.egg-info/dependency_links.txt +1 -0
- agentory-0.1.0/agentory.egg-info/requires.txt +10 -0
- agentory-0.1.0/agentory.egg-info/top_level.txt +1 -0
- agentory-0.1.0/pyproject.toml +28 -0
- agentory-0.1.0/setup.cfg +4 -0
- agentory-0.1.0/tests/test_agent.py +161 -0
- agentory-0.1.0/tests/test_mcp_schemas.py +103 -0
- agentory-0.1.0/tests/test_skills.py +85 -0
- agentory-0.1.0/tests/test_tool_schema_builder.py +156 -0
- agentory-0.1.0/tests/test_tool_views.py +113 -0
- agentory-0.1.0/tests/test_tools.py +121 -0
agentory-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mathis Kristoffer Arends
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
agentory-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentory
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal agent runtime with MCP integration, declarative tools, and streaming
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: py-llmify>=0.3.0
|
|
9
|
+
Provides-Extra: openai
|
|
10
|
+
Requires-Dist: py-llmify[openai]>=0.3.0; extra == "openai"
|
|
11
|
+
Provides-Extra: anthropic
|
|
12
|
+
Requires-Dist: py-llmify[anthropic]>=0.3.0; extra == "anthropic"
|
|
13
|
+
Provides-Extra: all
|
|
14
|
+
Requires-Dist: py-llmify[all]>=0.3.0; extra == "all"
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# agentory
|
|
18
|
+
|
|
19
|
+
A lightweight Python library for building tool-calling agents.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install agentory
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Install only the providers you actually need
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install "agentory[openai]" # + azure
|
|
31
|
+
pip install "agentory[anthropic]"
|
|
32
|
+
pip install "agentory[all]"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Requires Python 3.12+.
|
|
36
|
+
|
|
37
|
+
## Quickstart
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import asyncio
|
|
41
|
+
from llmify import ChatOpenAI
|
|
42
|
+
from agentory import Agent, Tools, ToolCallEvent
|
|
43
|
+
|
|
44
|
+
tools = Tools()
|
|
45
|
+
|
|
46
|
+
@tools.action("Return the current UTC time as an ISO-8601 string.")
|
|
47
|
+
def get_time() -> str:
|
|
48
|
+
from datetime import datetime, timezone
|
|
49
|
+
return datetime.now(timezone.utc).isoformat()
|
|
50
|
+
|
|
51
|
+
async def main():
|
|
52
|
+
llm = ChatOpenAI(model="gpt-5.4-mini")
|
|
53
|
+
agent = Agent(
|
|
54
|
+
instructions="You are a helpful assistant.",
|
|
55
|
+
llm=llm,
|
|
56
|
+
tools=tools,
|
|
57
|
+
)
|
|
58
|
+
async for event in agent.run("What time is it?"):
|
|
59
|
+
if isinstance(event, ToolCallEvent):
|
|
60
|
+
print(f"[tool] {event.tool_name}: {event.status}")
|
|
61
|
+
else:
|
|
62
|
+
print(event)
|
|
63
|
+
|
|
64
|
+
asyncio.run(main())
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Core API
|
|
68
|
+
|
|
69
|
+
### `Agent`
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
Agent(
|
|
73
|
+
instructions: str,
|
|
74
|
+
llm: ChatOpenAI | ChatAzureOpenAI | ChatAnthropic,
|
|
75
|
+
tools: Tools | None = None,
|
|
76
|
+
mcp_servers: list[MCPServer] | None = None,
|
|
77
|
+
skills: list[Skill] | None = None,
|
|
78
|
+
max_iterations: int = 10,
|
|
79
|
+
context: T | None = None,
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The main agent class. Call `agent.run(task)` to get an `AsyncIterator[StreamEvent]` that yields either plain `str` chunks or `ToolCallEvent` objects.
|
|
84
|
+
|
|
85
|
+
`context` is an arbitrary value injected into every tool function that declares a `context` parameter.
|
|
86
|
+
|
|
87
|
+
### `Tools`
|
|
88
|
+
|
|
89
|
+
A registry that turns plain functions into LLM-callable tools.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
tools = Tools()
|
|
93
|
+
|
|
94
|
+
@tools.action("Fetch the content of a URL.", status=lambda a: a["url"])
|
|
95
|
+
async def fetch(url: str) -> str:
|
|
96
|
+
...
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
- **`description`** – shown to the LLM in the tool schema.
|
|
100
|
+
- **`name`** – overrides the function name.
|
|
101
|
+
- **`status`** – a string or callable producing a human-readable status shown during streaming.
|
|
102
|
+
|
|
103
|
+
Type hints on parameters are automatically converted to JSON Schema. Use `Annotated[str, "description"]` to attach per-parameter descriptions.
|
|
104
|
+
|
|
105
|
+
### `Tool`
|
|
106
|
+
|
|
107
|
+
Low-level dataclass representing a single tool. Usually created via `Tools.action`; useful when constructing tools manually or from MCP servers.
|
|
108
|
+
|
|
109
|
+
### `Skill`
|
|
110
|
+
|
|
111
|
+
A piece of reusable instructions injected into the system prompt inside a `<skill>` block.
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from pathlib import Path
|
|
115
|
+
from agentory import Skill
|
|
116
|
+
|
|
117
|
+
skill = Skill.from_path(Path("my_skill.md"))
|
|
118
|
+
# or load SKILL.md from a directory:
|
|
119
|
+
skill = Skill.from_directory(Path("skills/my_skill/"))
|
|
120
|
+
|
|
121
|
+
agent = Agent(instructions="...", llm=llm, skills=[skill])
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Skill files use optional YAML frontmatter for `name` and `description`:
|
|
125
|
+
|
|
126
|
+
```markdown
|
|
127
|
+
---
|
|
128
|
+
name: web-search
|
|
129
|
+
description: Search the web for information
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
Use the search tool whenever the user asks about recent events...
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### `MCPServerStdio`
|
|
136
|
+
|
|
137
|
+
Connects to any [Model Context Protocol](https://modelcontextprotocol.io) server over stdio and exposes its tools to the agent.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from agentory import Agent, MCPServerStdio
|
|
141
|
+
|
|
142
|
+
server = MCPServerStdio(
|
|
143
|
+
command="npx",
|
|
144
|
+
args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
async with server:
|
|
148
|
+
agent = Agent(instructions="...", llm=llm, mcp_servers=[server])
|
|
149
|
+
async for event in agent.run("List files in /tmp"):
|
|
150
|
+
print(event)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Options:**
|
|
154
|
+
| Parameter | Default | Description |
|
|
155
|
+
|-----------|---------|-------------|
|
|
156
|
+
| `command` | — | Executable to spawn |
|
|
157
|
+
| `args` | `[]` | Arguments for the command |
|
|
158
|
+
| `env` | `None` | Extra environment variables (inherits current env when `None`) |
|
|
159
|
+
| `cache_tools_list` | `True` | Cache tool discovery after first call |
|
|
160
|
+
| `allowed_tools` | `None` | Whitelist of tool names to expose |
|
|
161
|
+
|
|
162
|
+
### `StreamEvent`
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
type StreamEvent = str | ToolCallEvent
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Events yielded by `agent.run()`. A plain `str` is a text chunk from the LLM; a `ToolCallEvent` signals that a tool is being called.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
@dataclass
|
|
172
|
+
class ToolCallEvent:
|
|
173
|
+
tool_name: str
|
|
174
|
+
status: str | None
|
|
175
|
+
```
|
agentory-0.1.0/README.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# agentory
|
|
2
|
+
|
|
3
|
+
A lightweight Python library for building tool-calling agents.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install agentory
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Install only the providers you actually need
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install "agentory[openai]" # + azure
|
|
15
|
+
pip install "agentory[anthropic]"
|
|
16
|
+
pip install "agentory[all]"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requires Python 3.12+.
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import asyncio
|
|
25
|
+
from llmify import ChatOpenAI
|
|
26
|
+
from agentory import Agent, Tools, ToolCallEvent
|
|
27
|
+
|
|
28
|
+
tools = Tools()
|
|
29
|
+
|
|
30
|
+
@tools.action("Return the current UTC time as an ISO-8601 string.")
|
|
31
|
+
def get_time() -> str:
|
|
32
|
+
from datetime import datetime, timezone
|
|
33
|
+
return datetime.now(timezone.utc).isoformat()
|
|
34
|
+
|
|
35
|
+
async def main():
|
|
36
|
+
llm = ChatOpenAI(model="gpt-5.4-mini")
|
|
37
|
+
agent = Agent(
|
|
38
|
+
instructions="You are a helpful assistant.",
|
|
39
|
+
llm=llm,
|
|
40
|
+
tools=tools,
|
|
41
|
+
)
|
|
42
|
+
async for event in agent.run("What time is it?"):
|
|
43
|
+
if isinstance(event, ToolCallEvent):
|
|
44
|
+
print(f"[tool] {event.tool_name}: {event.status}")
|
|
45
|
+
else:
|
|
46
|
+
print(event)
|
|
47
|
+
|
|
48
|
+
asyncio.run(main())
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Core API
|
|
52
|
+
|
|
53
|
+
### `Agent`
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
Agent(
|
|
57
|
+
instructions: str,
|
|
58
|
+
llm: ChatOpenAI | ChatAzureOpenAI | ChatAnthropic,
|
|
59
|
+
tools: Tools | None = None,
|
|
60
|
+
mcp_servers: list[MCPServer] | None = None,
|
|
61
|
+
skills: list[Skill] | None = None,
|
|
62
|
+
max_iterations: int = 10,
|
|
63
|
+
context: T | None = None,
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The main agent class. Call `agent.run(task)` to get an `AsyncIterator[StreamEvent]` that yields either plain `str` chunks or `ToolCallEvent` objects.
|
|
68
|
+
|
|
69
|
+
`context` is an arbitrary value injected into every tool function that declares a `context` parameter.
|
|
70
|
+
|
|
71
|
+
### `Tools`
|
|
72
|
+
|
|
73
|
+
A registry that turns plain functions into LLM-callable tools.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
tools = Tools()
|
|
77
|
+
|
|
78
|
+
@tools.action("Fetch the content of a URL.", status=lambda a: a["url"])
|
|
79
|
+
async def fetch(url: str) -> str:
|
|
80
|
+
...
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- **`description`** – shown to the LLM in the tool schema.
|
|
84
|
+
- **`name`** – overrides the function name.
|
|
85
|
+
- **`status`** – a string or callable producing a human-readable status shown during streaming.
|
|
86
|
+
|
|
87
|
+
Type hints on parameters are automatically converted to JSON Schema. Use `Annotated[str, "description"]` to attach per-parameter descriptions.
|
|
88
|
+
|
|
89
|
+
### `Tool`
|
|
90
|
+
|
|
91
|
+
Low-level dataclass representing a single tool. Usually created via `Tools.action`; useful when constructing tools manually or from MCP servers.
|
|
92
|
+
|
|
93
|
+
### `Skill`
|
|
94
|
+
|
|
95
|
+
A piece of reusable instructions injected into the system prompt inside a `<skill>` block.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from pathlib import Path
|
|
99
|
+
from agentory import Skill
|
|
100
|
+
|
|
101
|
+
skill = Skill.from_path(Path("my_skill.md"))
|
|
102
|
+
# or load SKILL.md from a directory:
|
|
103
|
+
skill = Skill.from_directory(Path("skills/my_skill/"))
|
|
104
|
+
|
|
105
|
+
agent = Agent(instructions="...", llm=llm, skills=[skill])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Skill files use optional YAML frontmatter for `name` and `description`:
|
|
109
|
+
|
|
110
|
+
```markdown
|
|
111
|
+
---
|
|
112
|
+
name: web-search
|
|
113
|
+
description: Search the web for information
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
Use the search tool whenever the user asks about recent events...
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### `MCPServerStdio`
|
|
120
|
+
|
|
121
|
+
Connects to any [Model Context Protocol](https://modelcontextprotocol.io) server over stdio and exposes its tools to the agent.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from agentory import Agent, MCPServerStdio
|
|
125
|
+
|
|
126
|
+
server = MCPServerStdio(
|
|
127
|
+
command="npx",
|
|
128
|
+
args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
async with server:
|
|
132
|
+
agent = Agent(instructions="...", llm=llm, mcp_servers=[server])
|
|
133
|
+
async for event in agent.run("List files in /tmp"):
|
|
134
|
+
print(event)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
**Options:**
|
|
138
|
+
| Parameter | Default | Description |
|
|
139
|
+
|-----------|---------|-------------|
|
|
140
|
+
| `command` | — | Executable to spawn |
|
|
141
|
+
| `args` | `[]` | Arguments for the command |
|
|
142
|
+
| `env` | `None` | Extra environment variables (inherits current env when `None`) |
|
|
143
|
+
| `cache_tools_list` | `True` | Cache tool discovery after first call |
|
|
144
|
+
| `allowed_tools` | `None` | Whitelist of tool names to expose |
|
|
145
|
+
|
|
146
|
+
### `StreamEvent`
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
type StreamEvent = str | ToolCallEvent
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Events yielded by `agent.run()`. A plain `str` is a text chunk from the LLM; a `ToolCallEvent` signals that a tool is being called.
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
@dataclass
|
|
156
|
+
class ToolCallEvent:
|
|
157
|
+
tool_name: str
|
|
158
|
+
status: str | None
|
|
159
|
+
```
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .agent import Agent
|
|
2
|
+
from .mcp import MCPServer, MCPServerStdio
|
|
3
|
+
from .skills import Skill
|
|
4
|
+
from .tools import Tools
|
|
5
|
+
from .tools.views import Tool
|
|
6
|
+
from .views import StreamEvent, ToolCallEvent
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Agent",
|
|
10
|
+
"MCPServer",
|
|
11
|
+
"MCPServerStdio",
|
|
12
|
+
"Skill",
|
|
13
|
+
"StreamEvent",
|
|
14
|
+
"Tool",
|
|
15
|
+
"ToolCallEvent",
|
|
16
|
+
"Tools",
|
|
17
|
+
]
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from llmify import ChatModel
|
|
9
|
+
from llmify.messages import (
|
|
10
|
+
AssistantMessage,
|
|
11
|
+
SystemMessage,
|
|
12
|
+
ToolResultMessage,
|
|
13
|
+
UserMessage,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from agentory.skills import Skill
|
|
17
|
+
from agentory.tools.tools import Tools
|
|
18
|
+
from agentory.views import StreamEvent, ToolCallEvent
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from agentory.mcp.server import MCPServer
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Agent[T]:
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
instructions: str,
|
|
31
|
+
llm: ChatModel,
|
|
32
|
+
tools: Tools | None = None,
|
|
33
|
+
mcp_servers: list[MCPServer] | None = None,
|
|
34
|
+
skills: list[Skill] | None = None,
|
|
35
|
+
max_iterations: int = 10,
|
|
36
|
+
context: T | None = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
self.llm = llm
|
|
39
|
+
self._instructions = instructions
|
|
40
|
+
self.tools = tools or Tools()
|
|
41
|
+
self.tools.set_context(context)
|
|
42
|
+
|
|
43
|
+
self._mcp_servers = mcp_servers or []
|
|
44
|
+
self._skills = skills or []
|
|
45
|
+
self._max_iterations = max_iterations
|
|
46
|
+
self._context: T | None = context
|
|
47
|
+
|
|
48
|
+
self._history = [SystemMessage(content=self._build_system_prompt())]
|
|
49
|
+
|
|
50
|
+
def _build_system_prompt(self) -> str:
|
|
51
|
+
if not self._skills:
|
|
52
|
+
return self._instructions
|
|
53
|
+
skills_block = "\n\n".join(skill.render() for skill in self._skills)
|
|
54
|
+
return f"{self._instructions}\n\n<skills>\n{skills_block}\n</skills>"
|
|
55
|
+
|
|
56
|
+
async def __aenter__(self) -> Agent[T]:
|
|
57
|
+
await self._connect_mcp_servers()
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
async def __aexit__(self, *_) -> None:
|
|
61
|
+
await self._cleanup_mcp_servers()
|
|
62
|
+
|
|
63
|
+
async def run(self, task: str) -> AsyncIterator[StreamEvent]:
|
|
64
|
+
self._history.append(UserMessage(content=task))
|
|
65
|
+
schema = self.tools.to_schema() or None
|
|
66
|
+
iterations = 0
|
|
67
|
+
|
|
68
|
+
while True:
|
|
69
|
+
if iterations >= self._max_iterations:
|
|
70
|
+
yield "[max iterations reached]"
|
|
71
|
+
return
|
|
72
|
+
iterations += 1
|
|
73
|
+
|
|
74
|
+
response = await self.llm.invoke(self._history, tools=schema)
|
|
75
|
+
|
|
76
|
+
if not response.tool_calls:
|
|
77
|
+
content = response.completion or ""
|
|
78
|
+
self._history.append(AssistantMessage(content=content))
|
|
79
|
+
yield content
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
self._history.append(
|
|
83
|
+
AssistantMessage(content=None, tool_calls=response.tool_calls)
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
for call in response.tool_calls:
|
|
87
|
+
tool = self.tools.get(call.function.name)
|
|
88
|
+
tool_args = json.loads(call.function.arguments)
|
|
89
|
+
yield ToolCallEvent(
|
|
90
|
+
tool_name=call.function.name,
|
|
91
|
+
status=tool.render_status(tool_args) if tool else None,
|
|
92
|
+
)
|
|
93
|
+
try:
|
|
94
|
+
result = await self.tools.execute(call.function.name, tool_args)
|
|
95
|
+
except Exception as e:
|
|
96
|
+
result = json.dumps({"error": str(e), "tool": call.function.name})
|
|
97
|
+
|
|
98
|
+
self._history.append(
|
|
99
|
+
ToolResultMessage(tool_call_id=call.id, content=result)
|
|
100
|
+
)
|
|
101
|
+
self._history.append(
|
|
102
|
+
ToolResultMessage(tool_call_id=call.id, content=result)
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def _connect_mcp_servers(self) -> None:
|
|
106
|
+
for server in self._mcp_servers:
|
|
107
|
+
await server.connect()
|
|
108
|
+
await self.tools.register_mcp_server(server)
|
|
109
|
+
|
|
110
|
+
async def _cleanup_mcp_servers(self) -> None:
|
|
111
|
+
for server in self._mcp_servers:
|
|
112
|
+
await server.cleanup()
|
|
113
|
+
|
|
114
|
+
def reset(self) -> None:
|
|
115
|
+
self._history = [SystemMessage(content=self._build_system_prompt())]
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class JsonRpcRequest(BaseModel):
|
|
7
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
8
|
+
|
|
9
|
+
jsonrpc: str = "2.0"
|
|
10
|
+
id: int
|
|
11
|
+
method: str
|
|
12
|
+
params: dict[str, Any] = Field(default_factory=dict)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class JsonRpcNotification(BaseModel):
|
|
16
|
+
jsonrpc: str = "2.0"
|
|
17
|
+
method: str
|
|
18
|
+
params: dict[str, Any] | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class JsonRpcError(BaseModel):
|
|
22
|
+
code: int
|
|
23
|
+
message: str
|
|
24
|
+
data: Any = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class JsonRpcResponse(BaseModel):
|
|
28
|
+
jsonrpc: str
|
|
29
|
+
id: int | None = None
|
|
30
|
+
result: dict[str, Any] | None = None
|
|
31
|
+
error: JsonRpcError | None = None
|
|
32
|
+
|
|
33
|
+
def unwrap(self) -> dict[str, Any]:
|
|
34
|
+
if self.error:
|
|
35
|
+
raise RuntimeError(f"MCP error: {self.error.model_dump()}")
|
|
36
|
+
return self.result or {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ClientInfo(BaseModel):
|
|
40
|
+
name: str
|
|
41
|
+
version: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class InitializeParams(BaseModel):
|
|
45
|
+
protocolVersion: str = "2024-11-05"
|
|
46
|
+
capabilities: dict[str, Any] = Field(default_factory=dict)
|
|
47
|
+
clientInfo: ClientInfo
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MCPServerStdioConfig(BaseModel):
|
|
51
|
+
command: str
|
|
52
|
+
args: list[str] = Field(default_factory=list)
|
|
53
|
+
env: dict[str, str] | None = None
|
|
54
|
+
cache_tools_list: bool = True
|
|
55
|
+
allowed_tools: list[str] | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class MCPToolInputSchema(BaseModel):
|
|
59
|
+
properties: dict[str, Any] = Field(default_factory=dict)
|
|
60
|
+
required: list[str] = Field(default_factory=list)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class MCPToolDefinition(BaseModel):
|
|
64
|
+
name: str
|
|
65
|
+
description: str | None = None
|
|
66
|
+
inputSchema: MCPToolInputSchema = Field(default_factory=MCPToolInputSchema)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class MCPToolsListResult(BaseModel):
|
|
70
|
+
tools: list[MCPToolDefinition] = Field(default_factory=list)
|