koder 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,141 @@
1
+ """MCP server configuration management."""
2
+
3
+ import os
4
+ from typing import List, Optional
5
+
6
+ import aiosqlite
7
+
8
+ from .server_config import MCPServerConfig
9
+
10
+
11
+ class MCPServerManager:
12
+ """Manages MCP server configurations in the database."""
13
+
14
+ def __init__(self, db_path: Optional[str] = None):
15
+ if db_path is None:
16
+ # Use the same path as ContextManager
17
+ home_dir = os.path.expanduser("~")
18
+ koder_dir = os.path.join(home_dir, ".koder")
19
+ os.makedirs(koder_dir, exist_ok=True)
20
+ self.db_path = os.path.join(koder_dir, "koder.db")
21
+ else:
22
+ self.db_path = db_path
23
+
24
+ async def _ensure_mcp_table(self, conn: aiosqlite.Connection) -> None:
25
+ """Ensure the MCP servers table exists."""
26
+ await conn.execute(
27
+ """CREATE TABLE IF NOT EXISTS mcp_servers (
28
+ name TEXT PRIMARY KEY,
29
+ transport_type TEXT NOT NULL,
30
+ command TEXT,
31
+ args TEXT,
32
+ env_vars TEXT,
33
+ url TEXT,
34
+ headers TEXT,
35
+ cache_tools_list INTEGER DEFAULT 0,
36
+ allowed_tools TEXT,
37
+ blocked_tools TEXT,
38
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
39
+ )"""
40
+ )
41
+ await conn.commit()
42
+
43
+ async def add_server(self, config: MCPServerConfig) -> None:
44
+ """Add a new MCP server configuration."""
45
+ data = config.to_db_dict()
46
+ async with aiosqlite.connect(self.db_path) as conn:
47
+ await self._ensure_mcp_table(conn)
48
+ await conn.execute(
49
+ """INSERT INTO mcp_servers
50
+ (name, transport_type, command, args, env_vars, url, headers,
51
+ cache_tools_list, allowed_tools, blocked_tools)
52
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
53
+ (
54
+ data["name"],
55
+ data["transport_type"],
56
+ data["command"],
57
+ data["args"],
58
+ data["env_vars"],
59
+ data["url"],
60
+ data["headers"],
61
+ data["cache_tools_list"],
62
+ data["allowed_tools"],
63
+ data["blocked_tools"],
64
+ ),
65
+ )
66
+ await conn.commit()
67
+
68
+ async def get_server(self, name: str) -> Optional[MCPServerConfig]:
69
+ """Get an MCP server configuration by name."""
70
+ async with aiosqlite.connect(self.db_path) as conn:
71
+ await self._ensure_mcp_table(conn)
72
+ conn.row_factory = aiosqlite.Row
73
+ cursor = await conn.execute("SELECT * FROM mcp_servers WHERE name = ?", (name,))
74
+ row = await cursor.fetchone()
75
+ if row:
76
+ return MCPServerConfig.from_db_dict(dict(row))
77
+ return None
78
+
79
+ async def list_servers(self) -> List[MCPServerConfig]:
80
+ """List all MCP server configurations."""
81
+ async with aiosqlite.connect(self.db_path) as conn:
82
+ await self._ensure_mcp_table(conn)
83
+ conn.row_factory = aiosqlite.Row
84
+ cursor = await conn.execute("SELECT * FROM mcp_servers ORDER BY name")
85
+ rows = await cursor.fetchall()
86
+ return [MCPServerConfig.from_db_dict(dict(row)) for row in rows]
87
+
88
+ async def update_server(self, config: MCPServerConfig) -> bool:
89
+ """Update an existing MCP server configuration."""
90
+ data = config.to_db_dict()
91
+ async with aiosqlite.connect(self.db_path) as conn:
92
+ await self._ensure_mcp_table(conn)
93
+ cursor = await conn.execute(
94
+ """UPDATE mcp_servers SET
95
+ transport_type = ?, command = ?, args = ?, env_vars = ?,
96
+ url = ?, headers = ?, cache_tools_list = ?,
97
+ allowed_tools = ?, blocked_tools = ?
98
+ WHERE name = ?""",
99
+ (
100
+ data["transport_type"],
101
+ data["command"],
102
+ data["args"],
103
+ data["env_vars"],
104
+ data["url"],
105
+ data["headers"],
106
+ data["cache_tools_list"],
107
+ data["allowed_tools"],
108
+ data["blocked_tools"],
109
+ data["name"],
110
+ ),
111
+ )
112
+ await conn.commit()
113
+ return cursor.rowcount > 0
114
+
115
+ async def remove_server(self, name: str) -> bool:
116
+ """Remove an MCP server configuration."""
117
+ async with aiosqlite.connect(self.db_path) as conn:
118
+ await self._ensure_mcp_table(conn)
119
+ cursor = await conn.execute("DELETE FROM mcp_servers WHERE name = ?", (name,))
120
+ await conn.commit()
121
+ return cursor.rowcount > 0
122
+
123
+ async def server_exists(self, name: str) -> bool:
124
+ """Check if a server with the given name exists."""
125
+ async with aiosqlite.connect(self.db_path) as conn:
126
+ await self._ensure_mcp_table(conn)
127
+ cursor = await conn.execute("SELECT 1 FROM mcp_servers WHERE name = ? LIMIT 1", (name,))
128
+ row = await cursor.fetchone()
129
+ return row is not None
130
+
131
+ async def get_servers_by_type(self, transport_type: str) -> List[MCPServerConfig]:
132
+ """Get all servers of a specific transport type."""
133
+ async with aiosqlite.connect(self.db_path) as conn:
134
+ await self._ensure_mcp_table(conn)
135
+ conn.row_factory = aiosqlite.Row
136
+ cursor = await conn.execute(
137
+ "SELECT * FROM mcp_servers WHERE transport_type = ? ORDER BY name",
138
+ (transport_type,),
139
+ )
140
+ rows = await cursor.fetchall()
141
+ return [MCPServerConfig.from_db_dict(dict(row)) for row in rows]
@@ -0,0 +1,98 @@
1
+ """Tool implementations for Koder Agent."""
2
+
3
+ from typing import List
4
+
5
+ from agents import Tool
6
+
7
+ from .engine import ToolEngine
8
+ from .file_ops import (
9
+ FileReadModel,
10
+ FileWriteModel,
11
+ LSModel,
12
+ append_file,
13
+ list_directory,
14
+ read_file,
15
+ write_file,
16
+ )
17
+ from .search_ops import GlobModel, GrepModel, glob_search, grep_search
18
+ from .shell_ops import GitModel, ShellModel, git_command, run_shell
19
+ from .task_ops import TaskDelegateModel, TaskModel, task_delegate
20
+ from .todo_ops import TodoModel, TodoWriteModel, todo_read, todo_write
21
+ from .web_ops import SearchModel, WebFetchModel, web_fetch, web_search
22
+
23
+ # Create the global tool engine
24
+ tool_engine = ToolEngine()
25
+
26
+ # Register all tools
27
+ tool_engine.register(FileReadModel)(read_file)
28
+ tool_engine.register(FileWriteModel)(write_file)
29
+ tool_engine.register(FileWriteModel)(append_file)
30
+ tool_engine.register(ShellModel)(run_shell)
31
+ tool_engine.register(SearchModel)(web_search)
32
+ tool_engine.register(GlobModel)(glob_search)
33
+ tool_engine.register(GrepModel)(grep_search)
34
+ tool_engine.register(LSModel)(list_directory)
35
+ tool_engine.register(TodoModel)(todo_read)
36
+ tool_engine.register(TodoWriteModel)(todo_write)
37
+ tool_engine.register(WebFetchModel)(web_fetch)
38
+ tool_engine.register(TaskDelegateModel)(task_delegate)
39
+ tool_engine.register(GitModel)(git_command)
40
+
41
+
42
+ def get_all_tools() -> List[Tool]:
43
+ """Get all registered tools as a list."""
44
+ # Collect all @function_tool decorated functions directly
45
+ tools = [
46
+ read_file,
47
+ write_file,
48
+ append_file,
49
+ run_shell,
50
+ git_command,
51
+ web_search,
52
+ web_fetch,
53
+ glob_search,
54
+ grep_search,
55
+ list_directory,
56
+ todo_read,
57
+ todo_write,
58
+ task_delegate,
59
+ ]
60
+
61
+ # Filter to only include properly decorated tools
62
+ return [tool for tool in tools if hasattr(tool, "name")]
63
+
64
+
65
+ __all__ = [
66
+ "tool_engine",
67
+ "get_all_tools",
68
+
69
+ # Models
70
+ "FileReadModel",
71
+ "FileWriteModel",
72
+ "LSModel",
73
+ "ShellModel",
74
+ "GitModel",
75
+ "SearchModel",
76
+ "WebFetchModel",
77
+ "GlobModel",
78
+ "GrepModel",
79
+ "TodoModel",
80
+ "TodoWriteModel",
81
+ "TaskModel",
82
+ "TaskDelegateModel",
83
+
84
+ # Functions
85
+ "read_file",
86
+ "write_file",
87
+ "append_file",
88
+ "run_shell",
89
+ "git_command",
90
+ "web_search",
91
+ "web_fetch",
92
+ "glob_search",
93
+ "grep_search",
94
+ "list_directory",
95
+ "todo_read",
96
+ "todo_write",
97
+ "task_delegate",
98
+ ]
@@ -0,0 +1,134 @@
1
+ """Tool engine for managing and executing tools."""
2
+
3
+ import asyncio
4
+ from typing import Any, Dict, Type
5
+
6
+ from pydantic import BaseModel, ValidationError
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+
10
+ from ..core.security import SecurityGuard
11
+
12
+ console = Console()
13
+
14
+
15
+ class ToolEngine:
16
+ """Engine for registering and executing tools with security checks."""
17
+
18
+ def __init__(self):
19
+ self.registry: Dict[str, Any] = {}
20
+ self.schemas: Dict[str, Type[BaseModel]] = {}
21
+
22
+ def register(self, schema: Type[BaseModel]):
23
+ """
24
+ Decorator factory for registering tools.
25
+
26
+ Usage:
27
+ @tool_engine.register(MySchema)
28
+ def my_tool(...):
29
+ ...
30
+ """
31
+
32
+ def decorator(fn: Any):
33
+ key = getattr(fn, "__name__", fn.__class__.__name__)
34
+ self.registry[key] = fn
35
+ self.schemas[key] = schema
36
+ return fn
37
+
38
+ return decorator
39
+
40
+ async def call(self, name: str, **kw) -> str:
41
+ """Execute a tool with security validation."""
42
+ # Show tool input
43
+ console.print(
44
+ Panel(
45
+ f"[bold cyan]Tool:[/bold cyan] {name}\n[bold cyan]Input:[/bold cyan] {kw}",
46
+ title="🔧 Tool Execution",
47
+ border_style="cyan",
48
+ )
49
+ )
50
+
51
+ if name not in self.registry:
52
+ result = f"Tool {name} not found"
53
+ console.print(Panel(f"[red]{result}[/red]", title="❌ Tool Error", border_style="red"))
54
+ return result
55
+
56
+ fn = self.registry[name]
57
+ schema = self.schemas[name]
58
+
59
+ # Validate parameters
60
+ try:
61
+ schema(**kw)
62
+ except ValidationError as e:
63
+ result = f"Param error {e}"
64
+ console.print(
65
+ Panel(f"[red]{result}[/red]", title="❌ Validation Error", border_style="red")
66
+ )
67
+ return result
68
+
69
+ # Security checks
70
+ if not self._validate_tool_name(name):
71
+ result = "No permission"
72
+ console.print(
73
+ Panel(f"[red]{result}[/red]", title="❌ Security Error", border_style="red")
74
+ )
75
+ return result
76
+
77
+ elif name == "run_shell":
78
+ error = SecurityGuard.validate_command(kw.get("command", ""))
79
+ if error:
80
+ console.print(
81
+ Panel(f"[red]{error}[/red]", title="❌ Security Error", border_style="red")
82
+ )
83
+ return error
84
+
85
+ try:
86
+ res = await asyncio.to_thread(fn, **kw)
87
+ except Exception as e:
88
+ res = f"Tool err {e}"
89
+
90
+ filtered_res = self._output_filter(str(res))
91
+
92
+ # Show tool output
93
+ if len(filtered_res) > 200:
94
+ display_res = filtered_res[:200] + "..."
95
+ else:
96
+ display_res = filtered_res
97
+
98
+ console.print(
99
+ Panel(
100
+ f"[dim blue]{display_res}[/dim blue]", title="✅ Tool Output", border_style="blue"
101
+ )
102
+ )
103
+
104
+ return filtered_res
105
+
106
+ def _validate_tool_name(self, name: str) -> bool:
107
+ """Validate tool name against allowed list."""
108
+ allowed_tools = {
109
+ "read_file",
110
+ "write_file",
111
+ "append_file",
112
+ "run_shell",
113
+ "web_search",
114
+ "glob_search",
115
+ "grep_search",
116
+ "list_directory",
117
+ "todo_read",
118
+ "todo_write",
119
+ "web_fetch",
120
+ "task_delegate",
121
+ "git_command",
122
+ }
123
+ return name in allowed_tools
124
+
125
+ def _output_filter(self, txt: str) -> str:
126
+ """Filter sensitive information from output."""
127
+ import re
128
+
129
+ # Filter API keys and tokens
130
+ txt = re.sub(r"sk-\w{10,}", "[TOKEN]", txt)
131
+ txt = re.sub(
132
+ r"(api[_-]?key|token|secret)[\s:=]+[\w-]{10,}", "[REDACTED]", txt, flags=re.IGNORECASE
133
+ )
134
+ return txt
@@ -0,0 +1,109 @@
1
+ """File operation tools."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ from agents import function_tool
7
+ from pydantic import BaseModel
8
+
9
+ from ..core.security import SecurityGuard
10
+
11
+
12
+ class FileWriteModel(BaseModel):
13
+ path: str
14
+ content: str
15
+
16
+
17
+ class FileReadModel(BaseModel):
18
+ path: str
19
+
20
+
21
+ class LSModel(BaseModel):
22
+ path: str
23
+ ignore: Optional[List[str]] = None
24
+
25
+
26
+ @function_tool
27
+ def read_file(path: str) -> str:
28
+ """Read a file from the filesystem."""
29
+ try:
30
+ p = Path(path).resolve()
31
+ if not p.exists():
32
+ return "File not found"
33
+
34
+ # Check file size
35
+ error = SecurityGuard.check_file_size(str(p))
36
+ if error:
37
+ return error
38
+
39
+ return p.read_text("utf-8", errors="ignore")
40
+ except PermissionError as e:
41
+ return str(e)
42
+ except Exception as e:
43
+ return f"Error reading file: {str(e)}"
44
+
45
+
46
+ @function_tool
47
+ def write_file(path: str, content: str) -> str:
48
+ """Write content to a file."""
49
+ try:
50
+ p = Path(path).resolve()
51
+ p.parent.mkdir(parents=True, exist_ok=True)
52
+ p.write_text(content, "utf-8")
53
+ return f"Wrote {len(content)} bytes to {path}"
54
+ except PermissionError as e:
55
+ return str(e)
56
+ except Exception as e:
57
+ return f"Error writing file: {str(e)}"
58
+
59
+
60
+ @function_tool
61
+ def append_file(path: str, content: str) -> str:
62
+ """Append content to a file."""
63
+ try:
64
+ p = Path(path).resolve()
65
+ p.parent.mkdir(parents=True, exist_ok=True)
66
+ with p.open("a", encoding="utf-8") as f:
67
+ f.write(content)
68
+ return f"Appended {len(content)} bytes to {path}"
69
+ except PermissionError as e:
70
+ return str(e)
71
+ except Exception as e:
72
+ return f"Error appending to file: {str(e)}"
73
+
74
+
75
+ @function_tool
76
+ def list_directory(path: str, ignore: Optional[List[str]] = None) -> str:
77
+ """List contents of a directory."""
78
+ try:
79
+ p = Path(path).resolve()
80
+ if not p.exists():
81
+ return "Path does not exist"
82
+ if not p.is_dir():
83
+ return "Path is not a directory"
84
+
85
+ ignore = ignore or []
86
+ items = []
87
+
88
+ for item in sorted(p.iterdir()):
89
+ # Skip ignored patterns
90
+ if any(pattern in item.name for pattern in ignore):
91
+ continue
92
+
93
+ if item.is_dir():
94
+ items.append(f"[DIR] {item.name}/")
95
+ else:
96
+ size = item.stat().st_size
97
+ if size < 1024:
98
+ size_str = f"{size}B"
99
+ elif size < 1024 * 1024:
100
+ size_str = f"{size / 1024:.1f}KB"
101
+ else:
102
+ size_str = f"{size / (1024 * 1024):.1f}MB"
103
+ items.append(f"[FILE] {item.name} ({size_str})")
104
+
105
+ return "\n".join(items) if items else "Directory is empty"
106
+ except PermissionError as e:
107
+ return str(e)
108
+ except Exception as e:
109
+ return f"Error listing directory: {str(e)}"
@@ -0,0 +1,141 @@
1
+ """File search operation tools."""
2
+
3
+ import fnmatch
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from agents import function_tool
9
+ from pydantic import BaseModel
10
+
11
+
12
+ class GlobModel(BaseModel):
13
+ pattern: str
14
+ path: Optional[str] = None
15
+
16
+
17
+ class GrepModel(BaseModel):
18
+ pattern: str
19
+ path: Optional[str] = None
20
+ include: Optional[str] = None
21
+
22
+
23
+ @function_tool
24
+ def glob_search(pattern: str, path: Optional[str] = None) -> str:
25
+ """Search for files matching a glob pattern."""
26
+ try:
27
+ base_path = Path(path) if path else Path.cwd()
28
+
29
+ # Validate base path
30
+ if not base_path.exists():
31
+ return f"Path does not exist: {base_path}"
32
+
33
+ if not base_path.is_dir():
34
+ return f"Path is not a directory: {base_path}"
35
+
36
+ # Find matches
37
+ matches = []
38
+
39
+ # Use rglob for recursive search if pattern contains **
40
+ if "**" in pattern:
41
+ matches = list(base_path.rglob(pattern.replace("**", "*")))
42
+ else:
43
+ matches = list(base_path.glob(pattern))
44
+
45
+ # Sort by modification time (newest first)
46
+ matches.sort(key=lambda p: p.stat().st_mtime, reverse=True)
47
+
48
+ # Limit results
49
+ matches = matches[:100]
50
+
51
+ if not matches:
52
+ return "No matches found"
53
+
54
+ # Format results
55
+ results = []
56
+ for match in matches:
57
+ try:
58
+ rel_path = match.relative_to(base_path)
59
+ if match.is_dir():
60
+ results.append(f"[DIR] {rel_path}/")
61
+ else:
62
+ size = match.stat().st_size
63
+ results.append(f"[FILE] {rel_path} ({size} bytes)")
64
+ except Exception:
65
+ results.append(str(match))
66
+
67
+ return "\n".join(results)
68
+
69
+ except Exception as e:
70
+ return f"Glob search error: {str(e)}"
71
+
72
+
73
+ @function_tool
74
+ def grep_search(pattern: str, path: Optional[str] = None, include: Optional[str] = None) -> str:
75
+ """Search for pattern in file contents."""
76
+ try:
77
+ base_path = Path(path) if path else Path.cwd()
78
+
79
+ # Validate base path
80
+ if not base_path.exists():
81
+ return f"Path does not exist: {base_path}"
82
+
83
+ # Compile regex pattern
84
+ try:
85
+ regex = re.compile(pattern)
86
+ except re.error as e:
87
+ return f"Invalid regex pattern: {str(e)}"
88
+
89
+ matches = []
90
+ files_searched = 0
91
+
92
+ # Search in files
93
+ for file_path in base_path.rglob("*"):
94
+ if not file_path.is_file():
95
+ continue
96
+
97
+ # Apply include filter if specified
98
+ if include and not fnmatch.fnmatch(file_path.name, include):
99
+ continue
100
+
101
+ # Skip binary files and large files
102
+ if file_path.stat().st_size > 1024 * 1024: # 1MB limit
103
+ continue
104
+
105
+ files_searched += 1
106
+ if files_searched > 1000: # Limit files searched
107
+ matches.append("... (search limited to 1000 files)")
108
+ break
109
+
110
+ try:
111
+ content = file_path.read_text(encoding="utf-8", errors="ignore")
112
+ if regex.search(content):
113
+ rel_path = file_path.relative_to(base_path)
114
+
115
+ # Find matching lines
116
+ lines = content.splitlines()
117
+ matching_lines = []
118
+ for i, line in enumerate(lines, 1):
119
+ if regex.search(line):
120
+ matching_lines.append(f" {i}: {line.strip()}")
121
+ if len(matching_lines) >= 3: # Show max 3 lines per file
122
+ matching_lines.append(" ...")
123
+ break
124
+
125
+ matches.append(f"\n{rel_path}:\n" + "\n".join(matching_lines))
126
+
127
+ if len(matches) >= 50: # Limit total results
128
+ matches.append("\n... (results limited to 50 files)")
129
+ break
130
+
131
+ except (UnicodeDecodeError, PermissionError):
132
+ # Skip files that can't be read
133
+ continue
134
+
135
+ if not matches:
136
+ return f"No matches found (searched {files_searched} files)"
137
+
138
+ return f"Pattern '{pattern}' found in {len(matches)} files:\n" + "\n".join(matches)
139
+
140
+ except Exception as e:
141
+ return f"Grep search error: {str(e)}"