modus-ai 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.
Files changed (77) hide show
  1. modus_ai-0.1.0/LICENSE +21 -0
  2. modus_ai-0.1.0/MANIFEST.in +10 -0
  3. modus_ai-0.1.0/PKG-INFO +169 -0
  4. modus_ai-0.1.0/README.md +135 -0
  5. modus_ai-0.1.0/modus/__init__.py +3 -0
  6. modus_ai-0.1.0/modus/actions/__init__.py +12 -0
  7. modus_ai-0.1.0/modus/actions/base.py +145 -0
  8. modus_ai-0.1.0/modus/actions/compaction.py +12 -0
  9. modus_ai-0.1.0/modus/actions/local.py +47 -0
  10. modus_ai-0.1.0/modus/actions/mcp/__init__.py +3 -0
  11. modus_ai-0.1.0/modus/actions/mcp/_stdio.py +79 -0
  12. modus_ai-0.1.0/modus/actions/mcp/client.py +103 -0
  13. modus_ai-0.1.0/modus/actions/mcp/transport.py +10 -0
  14. modus_ai-0.1.0/modus/actions/registry.py +63 -0
  15. modus_ai-0.1.0/modus/agent.py +355 -0
  16. modus_ai-0.1.0/modus/cli/__init__.py +3 -0
  17. modus_ai-0.1.0/modus/cli/_memory_cli.py +134 -0
  18. modus_ai-0.1.0/modus/core/__init__.py +4 -0
  19. modus_ai-0.1.0/modus/core/_validate.py +58 -0
  20. modus_ai-0.1.0/modus/core/protocols.py +49 -0
  21. modus_ai-0.1.0/modus/core/types.py +24 -0
  22. modus_ai-0.1.0/modus/deploy/__init__.py +4 -0
  23. modus_ai-0.1.0/modus/deploy/_scheduler.py +116 -0
  24. modus_ai-0.1.0/modus/deploy/_server.py +76 -0
  25. modus_ai-0.1.0/modus/memory/__init__.py +4 -0
  26. modus_ai-0.1.0/modus/memory/_chat.py +77 -0
  27. modus_ai-0.1.0/modus/memory/_memory.py +376 -0
  28. modus_ai-0.1.0/modus/memory/analysis/__init__.py +22 -0
  29. modus_ai-0.1.0/modus/memory/analysis/_analyzer.py +157 -0
  30. modus_ai-0.1.0/modus/memory/analysis/_vector.py +198 -0
  31. modus_ai-0.1.0/modus/memory/analysis/embeddings.py +159 -0
  32. modus_ai-0.1.0/modus/memory/bridges/__init__.py +8 -0
  33. modus_ai-0.1.0/modus/memory/bridges/_bridges.py +93 -0
  34. modus_ai-0.1.0/modus/memory/bridges/_langchain_memory.py +45 -0
  35. modus_ai-0.1.0/modus/memory/search/__init__.py +3 -0
  36. modus_ai-0.1.0/modus/memory/search/_scoring.py +76 -0
  37. modus_ai-0.1.0/modus/memory/storage/__init__.py +4 -0
  38. modus_ai-0.1.0/modus/memory/storage/_fts5.py +108 -0
  39. modus_ai-0.1.0/modus/memory/storage/_store.py +276 -0
  40. modus_ai-0.1.0/modus/orchestration/__init__.py +14 -0
  41. modus_ai-0.1.0/modus/orchestration/_state.py +90 -0
  42. modus_ai-0.1.0/modus/orchestration/_step.py +49 -0
  43. modus_ai-0.1.0/modus/orchestration/_team.py +154 -0
  44. modus_ai-0.1.0/modus/orchestration/_types.py +13 -0
  45. modus_ai-0.1.0/modus/orchestration/_workflow.py +458 -0
  46. modus_ai-0.1.0/modus/planner/__init__.py +4 -0
  47. modus_ai-0.1.0/modus/planner/_planner.py +98 -0
  48. modus_ai-0.1.0/modus/planner/_types.py +24 -0
  49. modus_ai-0.1.0/modus/providers/__init__.py +6 -0
  50. modus_ai-0.1.0/modus/providers/_factory.py +55 -0
  51. modus_ai-0.1.0/modus/providers/anthropic.py +92 -0
  52. modus_ai-0.1.0/modus/providers/gemini.py +187 -0
  53. modus_ai-0.1.0/modus/providers/openai.py +115 -0
  54. modus_ai-0.1.0/modus/safety/__init__.py +4 -0
  55. modus_ai-0.1.0/modus/safety/_interceptor.py +93 -0
  56. modus_ai-0.1.0/modus/safety/_policy.py +17 -0
  57. modus_ai-0.1.0/modus/skills/__init__.py +8 -0
  58. modus_ai-0.1.0/modus/skills/apply.py +90 -0
  59. modus_ai-0.1.0/modus/skills/loader.py +155 -0
  60. modus_ai-0.1.0/modus/skills/registry.py +74 -0
  61. modus_ai-0.1.0/modus/skills/types.py +27 -0
  62. modus_ai-0.1.0/modus/vision/__init__.py +4 -0
  63. modus_ai-0.1.0/modus/vision/_anthropic.py +66 -0
  64. modus_ai-0.1.0/modus/vision/_base.py +9 -0
  65. modus_ai-0.1.0/modus/vision/_gemini.py +42 -0
  66. modus_ai-0.1.0/modus/vision/_image.py +115 -0
  67. modus_ai-0.1.0/modus/vision/_ollama.py +65 -0
  68. modus_ai-0.1.0/modus/vision/_openai.py +53 -0
  69. modus_ai-0.1.0/modus/vision/_tesseract.py +35 -0
  70. modus_ai-0.1.0/modus/vision/_vision.py +89 -0
  71. modus_ai-0.1.0/modus_ai.egg-info/PKG-INFO +169 -0
  72. modus_ai-0.1.0/modus_ai.egg-info/SOURCES.txt +75 -0
  73. modus_ai-0.1.0/modus_ai.egg-info/dependency_links.txt +1 -0
  74. modus_ai-0.1.0/modus_ai.egg-info/requires.txt +11 -0
  75. modus_ai-0.1.0/modus_ai.egg-info/top_level.txt +1 -0
  76. modus_ai-0.1.0/pyproject.toml +79 -0
  77. modus_ai-0.1.0/setup.cfg +4 -0
modus_ai-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Modus Contributors
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ include LICENSE
2
+ include README.md
3
+ prune tests
4
+ prune yma
5
+ prune site
6
+ prune sample_projects
7
+ prune docs
8
+ prune assets
9
+ global-exclude *.py[cod]
10
+ global-exclude __pycache__/*
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: modus-ai
3
+ Version: 0.1.0
4
+ Summary: Modular AI agent framework
5
+ Author: Modus Contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ModusAgent/modus
8
+ Project-URL: Repository, https://github.com/ModusAgent/modus
9
+ Project-URL: Documentation, https://github.com/ModusAgent/modus#readme
10
+ Keywords: ai,agents,llm,framework,memory,mcp,orchestration
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: anthropic>=0.120.2
23
+ Requires-Dist: openai>=2.50.0
24
+ Requires-Dist: lancedb>=0.12.0
25
+ Requires-Dist: pyarrow>=15.0.0
26
+ Requires-Dist: mcp>=2.0.0
27
+ Requires-Dist: fastapi>=0.141.1
28
+ Requires-Dist: uvicorn>=0.52.0
29
+ Requires-Dist: apscheduler>=3.11.3
30
+ Requires-Dist: pillow>=12.3.0
31
+ Requires-Dist: google-genai>=2.16.0
32
+ Requires-Dist: pyyaml>=6.0.3
33
+ Dynamic: license-file
34
+
35
+ <p align="center">
36
+ <img src="assets/images/logo-dark-readme.png" alt="Modus" width="200">
37
+ <br><br>
38
+ <b>Modus — Modular AI agents. Composable by design.</b><br><br>
39
+ <img src="https://img.shields.io/badge/status-alpha-8B5CF6?style=for-the-badge" alt="Status">
40
+ <img src="https://img.shields.io/badge/Python-3.11%2B-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python">
41
+ <img src="https://img.shields.io/badge/tests-231%20passing-22C55E?style=for-the-badge" alt="Tests">
42
+ <img src="https://img.shields.io/badge/license-MIT-blue?style=for-the-badge" alt="MIT">
43
+ <br><br>
44
+ <b>Modus</b> is an open-source modular AI agent framework that provides reusable components<br>
45
+ for building, orchestrating, and deploying autonomous AI systems.<br><br>
46
+ Memory systems. Planning loops. Safety guards. Tool execution. MCP integration.<br>
47
+ All packaged as swappable modules with clear protocol boundaries.<br><br>
48
+ <a href="docs/index.md"><img src="https://img.shields.io/badge/Docs-8B5CF6?style=for-the-badge" alt="Docs"></a>
49
+ <a href="docs/modules/memory.md"><img src="https://img.shields.io/badge/Memory-22C55E?style=for-the-badge" alt="Memory"></a>
50
+ <a href="docs/guide/actions.md"><img src="https://img.shields.io/badge/Actions-3B82F6?style=for-the-badge" alt="Actions"></a>
51
+ <a href="docs/roadmap.md"><img src="https://img.shields.io/badge/Roadmap-F59E0B?style=for-the-badge" alt="Roadmap"></a>
52
+ </p>
53
+
54
+ ## Why Modus?
55
+
56
+ Building AI agents today means reinventing the same infrastructure every time: memory systems, planning loops, safety guards, tool execution, perception pipelines. Every framework forces you into a monolithic agent runtime where swapping one piece means rewriting half the system.
57
+
58
+ Modus takes the opposite approach.
59
+
60
+ Each capability is a self-contained module with a well-defined protocol interface. Swap memory backends without touching the planner. Change planning strategies without rewriting the action layer. Add safety policies without forking the codebase.
61
+
62
+ No vendor lock-in. No monolithic runtimes. Just composable building blocks.
63
+
64
+ ## Quick start
65
+
66
+ ```bash
67
+ pip install modus-ai
68
+ ```
69
+
70
+ ```python
71
+ from modus import Agent
72
+ from modus.memory import Memory
73
+ from modus.memory.analysis.embeddings import OpenAIEmbedding
74
+
75
+ agent = Agent(
76
+ name="Assistant",
77
+ instructions="You are a helpful assistant.",
78
+ provider="openai",
79
+ memory=Memory("./data", embedding=OpenAIEmbedding()),
80
+ )
81
+
82
+ # Memory context auto-injected, Chat auto-managed
83
+ response = agent.run("What do I know about Project Phoenix?")
84
+ ```
85
+
86
+ ## What's built
87
+
88
+ | Module | Features | Status |
89
+ |---|---|---|
90
+ | **Agent** | ReAct loop, Chat history, Memory injection, Tool calling, Event hooks | ✅ |
91
+ | **Memory** | OKF `.md` files, FTS5 keyword search, LanceDB vector search, Hybrid scoring, LLM analysis, entity extraction, TTL/eviction, Dreaming, consolidation, tenant isolation, concurrent writes | ✅ |
92
+ | **Actions** | Local tool registry, `@tool` decorator, MCP stdio/HTTP transport, argument validation, result compaction, caching, retry, timeout | ✅ |
93
+ | **Orchestration** | Workflow graph engine, dependency resolution, conditional routing, loops, HITL, state persistence, validation, hooks, async, sub-workflows, Mermaid export, context isolation | ✅ |
94
+ | **Deploy** | FastAPI webhook server, APScheduler (cron + interval) | ✅ |
95
+ | **Providers** | OpenAI + Anthropic with tool-call support, provider-agnostic protocol | ✅ |
96
+
97
+ ## Key architecture
98
+
99
+ - **Monorepo, single package:** `pip install modus-ai`
100
+ - **Memory:** OKF `.md` files + YAML frontmatter → FTS5 + LanceDB hybrid search
101
+ - **Actions:** Plugin local tools or connect MCP servers (`stdio` or `HTTP`)
102
+ - **ReAct loop:** Agent detects LLM tool calls, executes in parallel, feeds results back
103
+ - **Chat:** Token-budget conversation history, auto-summarized overflow
104
+ - **All modules are standalone:** `from modus.memory import Memory` — works without Agent
105
+
106
+ ## Example: Tools
107
+
108
+ ```python
109
+ from modus import Agent
110
+ from modus.actions import tool
111
+
112
+ @tool(name="get_weather", description="Get weather for a city", parameters={
113
+ "type": "object",
114
+ "properties": {"city": {"type": "string"}},
115
+ "required": ["city"],
116
+ })
117
+ def get_weather(city: str) -> str:
118
+ return f"Sunny, 25°C in {city}"
119
+
120
+ agent = Agent(name="WeatherBot", instructions="Use tools to answer questions.")
121
+ agent.actions.register(get_weather)
122
+
123
+ response = agent.run("What is the weather in Tokyo?")
124
+ ```
125
+
126
+ ## Example: MCP server
127
+
128
+ ```python
129
+ agent.actions.connect(
130
+ "filesystem",
131
+ command="npx",
132
+ args=["-y", "@modelcontextprotocol/server-filesystem", "."],
133
+ )
134
+ # Tools auto-discovered and available in the ReAct loop
135
+ ```
136
+
137
+ ## Example: Workflow with multiple agents
138
+
139
+ ```python
140
+ from modus.orchestration import Workflow, Step
141
+
142
+ workflow = Workflow(steps={
143
+ "classify": Step(agent=classifier, next={"billing": "resolve", "tech": "escalate"}),
144
+ "resolve": Step(agent=resolver, retry=2, timeout=30),
145
+ "respond": Step(agent=responder, depends_on=["resolve", "escalate"]),
146
+ })
147
+
148
+ result = workflow.run("I was charged twice")
149
+ ```
150
+
151
+ ## Documentation
152
+
153
+ | Section | Description |
154
+ |---|---|
155
+ | [Architecture](docs/architecture.md) | Block architecture and lifecycle |
156
+ | [Memory Guide](docs/modules/memory.md) | OKF concepts, storage, retrieval, API reference |
157
+ | [Actions Guide](docs/guide/actions.md) | MCP servers, tool execution, ReAct loop |
158
+ | [Protocol Reference](docs/reference/protocols.md) | Module interface contracts |
159
+ | [Contributing](docs/contributing.md) | Development guide and RFC process |
160
+ | [Roadmap](docs/roadmap.md) | Upcoming milestones |
161
+
162
+ ## Current status
163
+
164
+ **Alpha.** Agent, memory, actions, safety, planner, vision, skills, providers,
165
+ orchestration, and deploy are implemented and tested (280 tests).
166
+
167
+ ## License
168
+
169
+ MIT
@@ -0,0 +1,135 @@
1
+ <p align="center">
2
+ <img src="assets/images/logo-dark-readme.png" alt="Modus" width="200">
3
+ <br><br>
4
+ <b>Modus — Modular AI agents. Composable by design.</b><br><br>
5
+ <img src="https://img.shields.io/badge/status-alpha-8B5CF6?style=for-the-badge" alt="Status">
6
+ <img src="https://img.shields.io/badge/Python-3.11%2B-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python">
7
+ <img src="https://img.shields.io/badge/tests-231%20passing-22C55E?style=for-the-badge" alt="Tests">
8
+ <img src="https://img.shields.io/badge/license-MIT-blue?style=for-the-badge" alt="MIT">
9
+ <br><br>
10
+ <b>Modus</b> is an open-source modular AI agent framework that provides reusable components<br>
11
+ for building, orchestrating, and deploying autonomous AI systems.<br><br>
12
+ Memory systems. Planning loops. Safety guards. Tool execution. MCP integration.<br>
13
+ All packaged as swappable modules with clear protocol boundaries.<br><br>
14
+ <a href="docs/index.md"><img src="https://img.shields.io/badge/Docs-8B5CF6?style=for-the-badge" alt="Docs"></a>
15
+ <a href="docs/modules/memory.md"><img src="https://img.shields.io/badge/Memory-22C55E?style=for-the-badge" alt="Memory"></a>
16
+ <a href="docs/guide/actions.md"><img src="https://img.shields.io/badge/Actions-3B82F6?style=for-the-badge" alt="Actions"></a>
17
+ <a href="docs/roadmap.md"><img src="https://img.shields.io/badge/Roadmap-F59E0B?style=for-the-badge" alt="Roadmap"></a>
18
+ </p>
19
+
20
+ ## Why Modus?
21
+
22
+ Building AI agents today means reinventing the same infrastructure every time: memory systems, planning loops, safety guards, tool execution, perception pipelines. Every framework forces you into a monolithic agent runtime where swapping one piece means rewriting half the system.
23
+
24
+ Modus takes the opposite approach.
25
+
26
+ Each capability is a self-contained module with a well-defined protocol interface. Swap memory backends without touching the planner. Change planning strategies without rewriting the action layer. Add safety policies without forking the codebase.
27
+
28
+ No vendor lock-in. No monolithic runtimes. Just composable building blocks.
29
+
30
+ ## Quick start
31
+
32
+ ```bash
33
+ pip install modus-ai
34
+ ```
35
+
36
+ ```python
37
+ from modus import Agent
38
+ from modus.memory import Memory
39
+ from modus.memory.analysis.embeddings import OpenAIEmbedding
40
+
41
+ agent = Agent(
42
+ name="Assistant",
43
+ instructions="You are a helpful assistant.",
44
+ provider="openai",
45
+ memory=Memory("./data", embedding=OpenAIEmbedding()),
46
+ )
47
+
48
+ # Memory context auto-injected, Chat auto-managed
49
+ response = agent.run("What do I know about Project Phoenix?")
50
+ ```
51
+
52
+ ## What's built
53
+
54
+ | Module | Features | Status |
55
+ |---|---|---|
56
+ | **Agent** | ReAct loop, Chat history, Memory injection, Tool calling, Event hooks | ✅ |
57
+ | **Memory** | OKF `.md` files, FTS5 keyword search, LanceDB vector search, Hybrid scoring, LLM analysis, entity extraction, TTL/eviction, Dreaming, consolidation, tenant isolation, concurrent writes | ✅ |
58
+ | **Actions** | Local tool registry, `@tool` decorator, MCP stdio/HTTP transport, argument validation, result compaction, caching, retry, timeout | ✅ |
59
+ | **Orchestration** | Workflow graph engine, dependency resolution, conditional routing, loops, HITL, state persistence, validation, hooks, async, sub-workflows, Mermaid export, context isolation | ✅ |
60
+ | **Deploy** | FastAPI webhook server, APScheduler (cron + interval) | ✅ |
61
+ | **Providers** | OpenAI + Anthropic with tool-call support, provider-agnostic protocol | ✅ |
62
+
63
+ ## Key architecture
64
+
65
+ - **Monorepo, single package:** `pip install modus-ai`
66
+ - **Memory:** OKF `.md` files + YAML frontmatter → FTS5 + LanceDB hybrid search
67
+ - **Actions:** Plugin local tools or connect MCP servers (`stdio` or `HTTP`)
68
+ - **ReAct loop:** Agent detects LLM tool calls, executes in parallel, feeds results back
69
+ - **Chat:** Token-budget conversation history, auto-summarized overflow
70
+ - **All modules are standalone:** `from modus.memory import Memory` — works without Agent
71
+
72
+ ## Example: Tools
73
+
74
+ ```python
75
+ from modus import Agent
76
+ from modus.actions import tool
77
+
78
+ @tool(name="get_weather", description="Get weather for a city", parameters={
79
+ "type": "object",
80
+ "properties": {"city": {"type": "string"}},
81
+ "required": ["city"],
82
+ })
83
+ def get_weather(city: str) -> str:
84
+ return f"Sunny, 25°C in {city}"
85
+
86
+ agent = Agent(name="WeatherBot", instructions="Use tools to answer questions.")
87
+ agent.actions.register(get_weather)
88
+
89
+ response = agent.run("What is the weather in Tokyo?")
90
+ ```
91
+
92
+ ## Example: MCP server
93
+
94
+ ```python
95
+ agent.actions.connect(
96
+ "filesystem",
97
+ command="npx",
98
+ args=["-y", "@modelcontextprotocol/server-filesystem", "."],
99
+ )
100
+ # Tools auto-discovered and available in the ReAct loop
101
+ ```
102
+
103
+ ## Example: Workflow with multiple agents
104
+
105
+ ```python
106
+ from modus.orchestration import Workflow, Step
107
+
108
+ workflow = Workflow(steps={
109
+ "classify": Step(agent=classifier, next={"billing": "resolve", "tech": "escalate"}),
110
+ "resolve": Step(agent=resolver, retry=2, timeout=30),
111
+ "respond": Step(agent=responder, depends_on=["resolve", "escalate"]),
112
+ })
113
+
114
+ result = workflow.run("I was charged twice")
115
+ ```
116
+
117
+ ## Documentation
118
+
119
+ | Section | Description |
120
+ |---|---|
121
+ | [Architecture](docs/architecture.md) | Block architecture and lifecycle |
122
+ | [Memory Guide](docs/modules/memory.md) | OKF concepts, storage, retrieval, API reference |
123
+ | [Actions Guide](docs/guide/actions.md) | MCP servers, tool execution, ReAct loop |
124
+ | [Protocol Reference](docs/reference/protocols.md) | Module interface contracts |
125
+ | [Contributing](docs/contributing.md) | Development guide and RFC process |
126
+ | [Roadmap](docs/roadmap.md) | Upcoming milestones |
127
+
128
+ ## Current status
129
+
130
+ **Alpha.** Agent, memory, actions, safety, planner, vision, skills, providers,
131
+ orchestration, and deploy are implemented and tested (280 tests).
132
+
133
+ ## License
134
+
135
+ MIT
@@ -0,0 +1,3 @@
1
+ from modus.agent import Agent
2
+
3
+ __all__ = ["Agent"]
@@ -0,0 +1,12 @@
1
+ from modus.actions.base import Actions
2
+ from modus.actions.local import EchoTool, FunctionTool, tool
3
+ from modus.actions.registry import LocalToolRegistry, ToolRegistry
4
+
5
+ __all__ = [
6
+ "Actions",
7
+ "EchoTool",
8
+ "FunctionTool",
9
+ "LocalToolRegistry",
10
+ "ToolRegistry",
11
+ "tool",
12
+ ]
@@ -0,0 +1,145 @@
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import time
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from modus.actions.compaction import compact_result
9
+ from modus.actions.mcp.client import MCPClientManager
10
+ from modus.actions.registry import ToolRegistry
11
+ from modus.core.protocols import Tool
12
+ from modus.core.types import ToolDefinition
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def _validate_args(parameters: dict[str, Any] | None, args: dict[str, Any]) -> None:
18
+ if not parameters:
19
+ return
20
+ required = parameters.get("required", [])
21
+ missing = [field for field in required if field not in args]
22
+ if missing:
23
+ raise ValueError(f"Missing required arguments: {', '.join(missing)}")
24
+
25
+
26
+ def _normalize_result(result: Any) -> str:
27
+ if isinstance(result, str):
28
+ return result
29
+ return json.dumps(result, default=str)
30
+
31
+
32
+ class Actions:
33
+ def __init__(
34
+ self,
35
+ on_tool_call: Callable[[str, dict[str, Any]], None] | None = None,
36
+ on_approval: Callable[[str, dict[str, Any]], bool] | None = None,
37
+ ) -> None:
38
+ self._registry = ToolRegistry()
39
+ self._mcp = MCPClientManager()
40
+ self._cache: dict[str, dict[str, Any]] = {}
41
+ self._on_tool_call = on_tool_call
42
+ self._on_approval = on_approval
43
+ self._middleware: list[Callable] = []
44
+
45
+ def use(self, middleware_fn: Callable) -> None:
46
+ self._middleware.append(middleware_fn)
47
+
48
+ def register(self, tool: Tool) -> None:
49
+ self._registry.register(tool)
50
+
51
+ def connect(
52
+ self,
53
+ server: str,
54
+ *,
55
+ command: str | None = None,
56
+ args: list[str] | None = None,
57
+ url: str | None = None,
58
+ **kwargs: Any,
59
+ ) -> None:
60
+ self._mcp.connect(
61
+ server,
62
+ command=command,
63
+ args=args,
64
+ url=url,
65
+ **kwargs,
66
+ )
67
+
68
+ def list_tools(self) -> list[ToolDefinition]:
69
+ tools = self._registry.list_tools()
70
+ tools.extend(self._mcp.list_tools())
71
+ return tools
72
+
73
+ def to_openai_schemas(self) -> list[dict[str, Any]]:
74
+ return self._registry.to_openai_schemas()
75
+
76
+ def to_anthropic_schemas(self) -> list[dict[str, Any]]:
77
+ return self._registry.to_anthropic_schemas()
78
+
79
+ def execute(
80
+ self,
81
+ tool_name: str,
82
+ args: dict[str, Any],
83
+ timeout: int = 30,
84
+ retry: int = 2,
85
+ ) -> dict[str, Any]:
86
+ if self._on_tool_call:
87
+ self._on_tool_call(tool_name, args)
88
+
89
+ cache_key = _cache_key(tool_name, args)
90
+ if cache_key in self._cache:
91
+ return self._cache[cache_key]
92
+
93
+ for attempt in range(retry + 1):
94
+ try:
95
+ result = self._execute_once(tool_name, args, timeout)
96
+ self._cache[cache_key] = result
97
+ return result
98
+ except Exception as exc:
99
+ if attempt == retry:
100
+ return {"content": str(exc), "is_error": True}
101
+ time.sleep(0.5 * (attempt + 1))
102
+
103
+ return {"content": "Unexpected error", "is_error": True}
104
+
105
+ def _execute_once(self, tool_name: str, args: dict[str, Any], timeout: int) -> dict[str, Any]:
106
+ if self._registry.has(tool_name):
107
+ tool = self._registry.get(tool_name)
108
+
109
+ # Authorization check
110
+ require_approval = getattr(tool, "require_approval", False)
111
+ if require_approval and self._on_approval is not None:
112
+ approved = self._on_approval(tool_name, args)
113
+ if not approved:
114
+ logger.info("Tool '%s' rejected by approval callback", tool_name)
115
+ return {"content": f"Tool '{tool_name}' execution rejected", "is_error": True}
116
+
117
+ _validate_args(tool.parameters, args)
118
+
119
+ # Middleware chain
120
+ def call():
121
+ return tool.execute(**args)
122
+ for mw in reversed(self._middleware):
123
+ call = mw(call)
124
+ raw = call()
125
+
126
+ content = compact_result(_normalize_result(raw))
127
+ return {"content": content, "is_error": False}
128
+
129
+ if self._mcp.has_tool(tool_name):
130
+ raw = self._mcp.execute(tool_name, args, timeout=timeout)
131
+ content = compact_result(_normalize_result(raw))
132
+ return {"content": content, "is_error": False}
133
+
134
+ return {
135
+ "content": f"Unknown tool: {tool_name}",
136
+ "is_error": True,
137
+ }
138
+
139
+ def clear_cache(self) -> None:
140
+ self._cache.clear()
141
+
142
+
143
+ def _cache_key(tool_name: str, args: dict[str, Any]) -> str:
144
+ raw = f"{tool_name}:{json.dumps(args, sort_keys=True)}"
145
+ return hashlib.sha256(raw.encode()).hexdigest()
@@ -0,0 +1,12 @@
1
+ def compact_result(
2
+ content: str,
3
+ *,
4
+ max_chars: int = 12_000,
5
+ ) -> str:
6
+ """Shrink oversized tool output before returning it to the LLM."""
7
+ if len(content) <= max_chars:
8
+ return content
9
+ truncated = max_chars - 20
10
+ truncated = max(truncated, 0)
11
+ removed = len(content) - truncated
12
+ return f"{content[:truncated]}\n...[truncated {removed} chars]"
@@ -0,0 +1,47 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+
5
+
6
+ @dataclass
7
+ class FunctionTool:
8
+ name: str
9
+ description: str
10
+ parameters: dict[str, Any]
11
+ _fn: Callable[..., str] = field(repr=False)
12
+ require_approval: bool = False
13
+
14
+ def execute(self, **kwargs: Any) -> str:
15
+ return self._fn(**kwargs)
16
+
17
+
18
+ def tool(
19
+ name: str,
20
+ description: str,
21
+ parameters: dict[str, Any],
22
+ require_approval: bool = False,
23
+ ) -> Callable[[Callable[..., str]], FunctionTool]:
24
+ def decorator(fn: Callable[..., str]) -> FunctionTool:
25
+ return FunctionTool(
26
+ name=name,
27
+ description=description,
28
+ parameters=parameters,
29
+ require_approval=require_approval,
30
+ _fn=fn,
31
+ )
32
+
33
+ return decorator
34
+
35
+
36
+ class EchoTool:
37
+ name = "echo"
38
+ description = "Echo back the input message"
39
+ parameters = {
40
+ "type": "object",
41
+ "properties": {"message": {"type": "string"}},
42
+ "required": ["message"],
43
+ }
44
+ require_approval = False
45
+
46
+ def execute(self, *, message: str) -> str:
47
+ return message
@@ -0,0 +1,3 @@
1
+ from modus.actions.mcp.client import MCPClientManager
2
+
3
+ __all__ = ["MCPClientManager"]
@@ -0,0 +1,79 @@
1
+ import json
2
+ import logging
3
+ import subprocess
4
+ from typing import Any
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class MCPStdioServer:
10
+ def __init__(self, command: str, args: list[str] | None = None) -> None:
11
+ self._command = command
12
+ self._args = args or []
13
+ self._process: subprocess.Popen | None = None
14
+
15
+ def start(self) -> None:
16
+ self._process = subprocess.Popen(
17
+ [self._command, *self._args],
18
+ stdin=subprocess.PIPE,
19
+ stdout=subprocess.PIPE,
20
+ stderr=subprocess.PIPE,
21
+ text=True,
22
+ )
23
+
24
+ def send(self, request: dict[str, Any]) -> dict[str, Any]:
25
+ if self._process is None or self._process.stdin is None:
26
+ raise RuntimeError("Server not started")
27
+ line = json.dumps(request) + "\n"
28
+ self._process.stdin.write(line)
29
+ self._process.stdin.flush()
30
+ raw = self._process.stdout.readline() if self._process.stdout else ""
31
+ if not raw:
32
+ raise ConnectionError("MCP server closed connection")
33
+ return json.loads(raw)
34
+
35
+ def close(self) -> None:
36
+ if self._process:
37
+ self._process.terminate()
38
+ self._process.wait(timeout=5)
39
+
40
+ def list_tools(self) -> list[dict[str, Any]]:
41
+ resp = self.send({"jsonrpc": "2.0", "method": "tools/list", "id": 1})
42
+ return resp.get("result", {}).get("tools", [])
43
+
44
+ def call_tool(self, name: str, args: dict[str, Any], timeout: int = 30) -> str:
45
+ if self._process is None or self._process.stdout is None:
46
+ raise RuntimeError("Server not started")
47
+ request = json.dumps({
48
+ "jsonrpc": "2.0",
49
+ "method": "tools/call",
50
+ "params": {"name": name, "arguments": args},
51
+ "id": 2,
52
+ }) + "\n"
53
+ self._process.stdin.write(request)
54
+ self._process.stdin.flush()
55
+ try:
56
+ self._process.stdout.flush()
57
+ except Exception:
58
+ logger.debug("Failed to flush stdout stream")
59
+ raw = self._read_line_with_timeout(timeout)
60
+ if not raw:
61
+ self.close()
62
+ raise TimeoutError(f"Tool '{name}' timed out after {timeout}s")
63
+ resp = json.loads(raw)
64
+ result = resp.get("result", {})
65
+ content = result.get("content", [])
66
+ parts = [c.get("text", "") for c in content if c.get("type") == "text"]
67
+ return "\n".join(parts)
68
+
69
+ def _read_line_with_timeout(self, timeout: int) -> str:
70
+ import select
71
+ if self._process is None or self._process.stdout is None:
72
+ return ""
73
+ import time
74
+ deadline = time.time() + timeout
75
+ while time.time() < deadline:
76
+ r, _, _ = select.select([self._process.stdout], [], [], 1.0)
77
+ if r:
78
+ return self._process.stdout.readline()
79
+ return ""