brawler-mcp-server-python 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,12 @@
1
+ """FastMCP wrapper that stamps agent task metadata on MCP tools."""
2
+
3
+ from brawler_mcp_server.server import BrawlerMCP
4
+ from brawler_mcp_server.utils import META_NAMESPACE, AgentTask, task_from_meta, tools_for_task
5
+
6
+ __all__ = [
7
+ 'META_NAMESPACE',
8
+ 'AgentTask',
9
+ 'BrawlerMCP',
10
+ 'task_from_meta',
11
+ 'tools_for_task',
12
+ ]
@@ -0,0 +1,134 @@
1
+ """FastMCP subclass with Brawler agent-task decorators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any, TypeVar, overload
7
+
8
+ from fastmcp import FastMCP
9
+ from fastmcp.tools.function_tool import FunctionTool
10
+
11
+ from brawler_mcp_server.tasks import (
12
+ CompletionTask,
13
+ ContextTask,
14
+ EvaluationTask,
15
+ NoneTask,
16
+ PostTask,
17
+ )
18
+ from brawler_mcp_server.utils import AgentTask, TaskHandler, stamp_task_kwargs, tools_for_task
19
+
20
+ F = TypeVar('F', bound=Callable[..., Any])
21
+
22
+
23
+ class BrawlerMCP(FastMCP):
24
+ """FastMCP server that stamps agent tasks on tools.
25
+
26
+ ``@mcp.tool`` is completion. Use ``@context_tool``, ``@eval_tool``,
27
+ ``@post_tool``, and ``@none_tool`` for the other agent tasks.
28
+ FastMCP's ``task=`` keyword on ``tool()`` still means a background MCP task,
29
+ not a Brawler agent task.
30
+ """
31
+
32
+ def tool(
33
+ self,
34
+ name_or_fn: str | Callable[..., Any] | None = None,
35
+ *,
36
+ name: str | None = None,
37
+ tags: set[str] | None = None,
38
+ meta: dict[str, Any] | None = None,
39
+ **kwargs: Any,
40
+ ) -> Any:
41
+ """Register a completion tool (FastMCP ``@tool`` plus task metadata)."""
42
+ if name is not None:
43
+ kwargs['name'] = name
44
+ kwargs['tags'] = tags
45
+ kwargs['meta'] = meta
46
+ return self._task_tool(name_or_fn, CompletionTask(), **kwargs)
47
+
48
+ @overload
49
+ def context_tool(self, name_or_fn: F, /, *, as_user_message: bool = ...) -> F: ...
50
+
51
+ @overload
52
+ def context_tool(
53
+ self, name_or_fn: str | None = None, /, *, as_user_message: bool = ..., **kwargs: Any
54
+ ) -> Callable[[F], F]: ...
55
+
56
+ def context_tool(
57
+ self,
58
+ name_or_fn: str | Callable[..., Any] | None = None,
59
+ /,
60
+ *,
61
+ as_user_message: bool = False,
62
+ **kwargs: Any,
63
+ ) -> Any:
64
+ """Register a context tool that must return ``str``."""
65
+ return self._task_tool(name_or_fn, ContextTask(as_user_message=as_user_message), **kwargs)
66
+
67
+ @overload
68
+ def eval_tool(self, name_or_fn: F, /) -> F: ...
69
+
70
+ @overload
71
+ def eval_tool(self, name_or_fn: str | None = None, /, **kwargs: Any) -> Callable[[F], F]: ...
72
+
73
+ def eval_tool(
74
+ self,
75
+ name_or_fn: str | Callable[..., Any] | None = None,
76
+ /,
77
+ **kwargs: Any,
78
+ ) -> Any:
79
+ """Register an evaluation tool that returns ``tuple[bool, float, str | None]``."""
80
+ return self._task_tool(name_or_fn, EvaluationTask(), **kwargs)
81
+
82
+ @overload
83
+ def post_tool(self, name_or_fn: F, /) -> F: ...
84
+
85
+ @overload
86
+ def post_tool(self, name_or_fn: str | None = None, /, **kwargs: Any) -> Callable[[F], F]: ...
87
+
88
+ def post_tool(
89
+ self,
90
+ name_or_fn: str | Callable[..., Any] | None = None,
91
+ /,
92
+ **kwargs: Any,
93
+ ) -> Any:
94
+ """Register a post-result side-effect tool that must return ``None``."""
95
+ return self._task_tool(name_or_fn, PostTask(), **kwargs)
96
+
97
+ @overload
98
+ def none_tool(self, name_or_fn: F, /) -> F: ...
99
+
100
+ @overload
101
+ def none_tool(self, name_or_fn: str | None = None, /, **kwargs: Any) -> Callable[[F], F]: ...
102
+
103
+ def none_tool(
104
+ self,
105
+ name_or_fn: str | Callable[..., Any] | None = None,
106
+ /,
107
+ **kwargs: Any,
108
+ ) -> Any:
109
+ """Register a tool that Brawler agents ignore."""
110
+ return self._task_tool(name_or_fn, NoneTask(), **kwargs)
111
+
112
+ async def tools_by_task(self, task: AgentTask | str) -> list[Any]:
113
+ """Return in-process tools whose stamped agent task matches *task*."""
114
+ tools = await self.list_tools()
115
+ return tools_for_task(tools, task)
116
+
117
+ def _task_tool(
118
+ self,
119
+ name_or_fn: str | Callable[..., Any] | None,
120
+ handler: TaskHandler,
121
+ **kwargs: Any,
122
+ ) -> Any:
123
+ if isinstance(name_or_fn, str):
124
+ kwargs.setdefault('name', name_or_fn)
125
+ name_or_fn = None
126
+ stamped = stamp_task_kwargs(kwargs, handler.task, extra=handler.extra_meta())
127
+
128
+ def apply(fn: Callable[..., Any]) -> FunctionTool | Callable[..., Any]:
129
+ handler.check(fn)
130
+ return super(BrawlerMCP, self).tool(handler.wrap(fn), **stamped)
131
+
132
+ if callable(name_or_fn):
133
+ return apply(name_or_fn)
134
+ return apply
@@ -0,0 +1,17 @@
1
+ """One handler class per agent task."""
2
+
3
+ from brawler_mcp_server.tasks.completion import CompletionTask
4
+ from brawler_mcp_server.tasks.context import ContextTask
5
+ from brawler_mcp_server.tasks.evaluation import EvaluationTask
6
+ from brawler_mcp_server.tasks.none import NoneTask
7
+ from brawler_mcp_server.tasks.post import PostTask
8
+ from brawler_mcp_server.utils import AgentTask
9
+
10
+ __all__ = [
11
+ 'AgentTask',
12
+ 'CompletionTask',
13
+ 'ContextTask',
14
+ 'EvaluationTask',
15
+ 'NoneTask',
16
+ 'PostTask',
17
+ ]
@@ -0,0 +1,12 @@
1
+ """Completion task: model-callable tools, FastMCP default return types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from brawler_mcp_server.utils import AgentTask, TaskHandler
6
+
7
+
8
+ class CompletionTask(TaskHandler):
9
+ """Stamp completion metadata; return types follow FastMCP defaults."""
10
+
11
+ task = AgentTask.COMPLETION
12
+ label = 'Completion tool'
@@ -0,0 +1,34 @@
1
+ """Context task: prompt or user-message injection, return ``str``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from brawler_mcp_server.utils import AgentTask, TaskHandler, require_return_type, wrap_checked
9
+
10
+
11
+ class ContextTask(TaskHandler):
12
+ """Validate and wrap context tools that must return ``str``."""
13
+
14
+ task = AgentTask.CONTEXT
15
+ label = 'Context tool'
16
+
17
+ def __init__(self, *, as_user_message: bool = False) -> None:
18
+ self.as_user_message = as_user_message
19
+
20
+ def extra_meta(self) -> dict[str, Any]:
21
+ return {'as_user_message': self.as_user_message}
22
+
23
+ def check(self, fn: Callable[..., Any]) -> None:
24
+ require_return_type(fn, str, label=self.label)
25
+
26
+ def wrap(self, fn: Callable[..., Any]) -> Callable[..., Any]:
27
+ name = getattr(fn, '__name__', '<tool>')
28
+
29
+ def check(result: Any) -> str:
30
+ if not isinstance(result, str):
31
+ raise TypeError(f'{self.label} {name!r} must return str, got {type(result).__name__}.')
32
+ return result
33
+
34
+ return wrap_checked(fn, check)
@@ -0,0 +1,74 @@
1
+ """Evaluation task: ``tuple[bool, float, str | None]`` serialized as JSON."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Callable
7
+ from typing import Any, TypedDict, get_args, get_origin
8
+
9
+ from brawler_mcp_server.utils import AgentTask, TaskHandler, return_annotation, wrap_checked
10
+
11
+ EVAL_RETURN = 'tuple[bool, float, str | None]'
12
+
13
+
14
+ class EvalResult(TypedDict):
15
+ """JSON payload returned by evaluation tools."""
16
+
17
+ is_valid: bool
18
+ score: float
19
+ feedback: str | None
20
+
21
+
22
+ class EvaluationTask(TaskHandler):
23
+ """Validate and wrap eval tools that return ``tuple[bool, float, str | None]``."""
24
+
25
+ task = AgentTask.EVALUATION
26
+ label = 'Eval tool'
27
+
28
+ def check(self, fn: Callable[..., Any]) -> None:
29
+ annotation = return_annotation(fn)
30
+ if annotation is inspect.Signature.empty:
31
+ raise TypeError(f'{self.label} {fn.__name__!r} must return {EVAL_RETURN}, got unannotated.')
32
+ if not is_eval_tuple(annotation):
33
+ raise TypeError(f'{self.label} {fn.__name__!r} must return {EVAL_RETURN}, got {annotation}.')
34
+
35
+ def wrap(self, fn: Callable[..., Any]) -> Callable[..., Any]:
36
+ wrapped = wrap_checked(fn, eval_tuple_to_payload)
37
+ wrapped.__annotations__ = {**getattr(fn, '__annotations__', {}), 'return': EvalResult}
38
+ return wrapped
39
+
40
+
41
+ def eval_tuple_to_payload(result: Any) -> EvalResult:
42
+ """Validate and convert an eval function result to the wire dict."""
43
+ if isinstance(result, dict) and {'is_valid', 'score', 'feedback'} <= set(result):
44
+ return _eval_payload(result['is_valid'], result['score'], result.get('feedback'))
45
+ if not isinstance(result, tuple) or len(result) != 3:
46
+ raise TypeError(f'Eval tool must return {EVAL_RETURN}, got {type(result).__name__}.')
47
+ return _eval_payload(*result)
48
+
49
+
50
+ def is_eval_tuple(annotation: Any) -> bool:
51
+ """Return True when *annotation* is ``tuple[bool, float, str | None]`` (or str/None feedback)."""
52
+ origin = get_origin(annotation)
53
+ if origin is not tuple:
54
+ return False
55
+ args = get_args(annotation)
56
+ if len(args) != 3:
57
+ return False
58
+ is_valid_t, score_t, feedback_t = args
59
+ if is_valid_t is not bool or score_t is not float:
60
+ return False
61
+ if feedback_t in (str, type(None)):
62
+ return True
63
+ union_args = get_args(feedback_t)
64
+ return set(union_args) == {str, type(None)}
65
+
66
+
67
+ def _eval_payload(is_valid: Any, score: Any, feedback: Any) -> EvalResult:
68
+ if not isinstance(is_valid, bool):
69
+ raise TypeError(f'Eval is_valid must be bool, got {type(is_valid).__name__}.')
70
+ if isinstance(score, bool) or not isinstance(score, (int, float)):
71
+ raise TypeError(f'Eval score must be float, got {type(score).__name__}.')
72
+ if feedback is not None and not isinstance(feedback, str):
73
+ raise TypeError(f'Eval feedback must be str | None, got {type(feedback).__name__}.')
74
+ return EvalResult(is_valid=is_valid, score=float(score), feedback=feedback)
@@ -0,0 +1,12 @@
1
+ """None task: generic MCP tools that Brawler agents ignore."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from brawler_mcp_server.utils import AgentTask, TaskHandler
6
+
7
+
8
+ class NoneTask(TaskHandler):
9
+ """Stamp none metadata; Brawler agents never call these tools."""
10
+
11
+ task = AgentTask.NONE
12
+ label = 'None tool'
@@ -0,0 +1,28 @@
1
+ """Post task: side effects after a result, return ``None``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from brawler_mcp_server.utils import AgentTask, TaskHandler, require_return_type, wrap_checked
9
+
10
+
11
+ class PostTask(TaskHandler):
12
+ """Validate and wrap post tools that must return ``None``."""
13
+
14
+ task = AgentTask.POST_TOOL
15
+ label = 'Post tool'
16
+
17
+ def check(self, fn: Callable[..., Any]) -> None:
18
+ require_return_type(fn, type(None), label=self.label)
19
+
20
+ def wrap(self, fn: Callable[..., Any]) -> Callable[..., Any]:
21
+ name = getattr(fn, '__name__', '<tool>')
22
+
23
+ def check(result: Any) -> None:
24
+ if result is not None:
25
+ raise TypeError(f'{self.label} {name!r} must return None, got {type(result).__name__}.')
26
+ return result
27
+
28
+ return wrap_checked(fn, check)
@@ -0,0 +1,74 @@
1
+ """Test helpers for this package (import via ``brawler_mcp_server.testkit``, not ``tests.*``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from brawler_mcp_server import BrawlerMCP
8
+
9
+
10
+ def example_server() -> BrawlerMCP:
11
+ """Build a mixed-task server used by listing and call tests."""
12
+ mcp = BrawlerMCP('TestServer')
13
+
14
+ @mcp.context_tool
15
+ def policies() -> str:
16
+ return 'Always cite sources.'
17
+
18
+ @mcp.context_tool(as_user_message=True)
19
+ def ticket() -> str:
20
+ return 'Ticket #123 is still open.'
21
+
22
+ @mcp.tool
23
+ def echo(text: str) -> str:
24
+ return text
25
+
26
+ @mcp.eval_tool
27
+ def grounded(answer: str) -> tuple[bool, float, str | None]:
28
+ if not str(answer).strip():
29
+ return False, 0.0, 'Answer is empty.'
30
+ return True, 1.0, None
31
+
32
+ @mcp.post_tool
33
+ def audit(answer: str) -> None:
34
+ return None
35
+
36
+ @mcp.none_tool
37
+ def ping() -> str:
38
+ return 'pong'
39
+
40
+ return mcp
41
+
42
+
43
+ def call_text(result: object) -> str:
44
+ """Extract concatenated text from a FastMCP call result."""
45
+ content = getattr(result, 'content', None)
46
+ if content:
47
+ texts = [getattr(item, 'text', '') for item in content if getattr(item, 'text', None)]
48
+ if texts:
49
+ return '\n'.join(texts)
50
+ data = getattr(result, 'data', None)
51
+ if data is not None:
52
+ return str(data)
53
+ structured = getattr(result, 'structured_content', None) or getattr(result, 'structuredContent', None)
54
+ if structured is not None:
55
+ return str(structured)
56
+ return str(result)
57
+
58
+
59
+ def json_payload(result: object) -> dict:
60
+ """Parse an eval tool call into ``is_valid`` / ``score`` / ``feedback``."""
61
+ structured = getattr(result, 'structured_content', None) or getattr(result, 'structuredContent', None)
62
+ if isinstance(structured, dict) and 'is_valid' in structured:
63
+ return structured
64
+ data = getattr(result, 'data', None)
65
+ if isinstance(data, dict) and 'is_valid' in data:
66
+ return data
67
+ text = call_text(result)
68
+ try:
69
+ parsed = json.loads(text)
70
+ except json.JSONDecodeError:
71
+ parsed = None
72
+ if isinstance(parsed, dict):
73
+ return parsed
74
+ raise AssertionError(f'Could not parse eval payload from {result!r}')
@@ -0,0 +1,161 @@
1
+ """Shared helpers for task metadata, annotations, and return wrapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Callable, Iterable, Sequence
7
+ from enum import Enum
8
+ from functools import wraps
9
+ from typing import Any, ClassVar, get_type_hints
10
+
11
+ META_NAMESPACE = 'mcp_server'
12
+ _Check = Callable[[Any], Any]
13
+
14
+
15
+ class AgentTask(str, Enum):
16
+ """Tasks a Brawler agent can consume from an MCP server."""
17
+
18
+ CONTEXT = 'context'
19
+ COMPLETION = 'completion'
20
+ EVALUATION = 'evaluation'
21
+ POST_TOOL = 'post_tool'
22
+ NONE = 'none'
23
+
24
+
25
+ AGENT_TASK_VALUES = frozenset(task.value for task in AgentTask)
26
+
27
+
28
+ class TaskHandler:
29
+ """Validates and wraps a tool function for one agent task."""
30
+
31
+ task: ClassVar[AgentTask]
32
+ label: ClassVar[str]
33
+
34
+ def extra_meta(self) -> dict[str, Any]:
35
+ """Return task-specific ``_meta.mcp_server`` fields."""
36
+ return {}
37
+
38
+ def check(self, fn: Callable[..., Any]) -> None:
39
+ """Validate *fn*'s return annotation. Override in subclasses."""
40
+
41
+ def wrap(self, fn: Callable[..., Any]) -> Callable[..., Any]:
42
+ """Wrap *fn* to validate its runtime return value. Override in subclasses."""
43
+ return fn
44
+
45
+
46
+ def require_return_type(fn: Callable[..., Any], expected: type | tuple[type, ...], *, label: str) -> None:
47
+ """Raise TypeError when *fn* is not annotated with *expected*."""
48
+ annotation = return_annotation(fn)
49
+ if annotation is inspect.Signature.empty:
50
+ raise TypeError(f'{label} {fn.__name__!r} must declare a return type of {expected}.')
51
+ if not annotation_matches(annotation, expected):
52
+ raise TypeError(f'{label} {fn.__name__!r} must return {expected}, got {annotation}.')
53
+
54
+
55
+ def wrap_checked(fn: Callable[..., Any], check: _Check) -> Callable[..., Any]:
56
+ """Wrap *fn* so *check* runs on its return value (sync or async)."""
57
+ if inspect.iscoroutinefunction(fn):
58
+
59
+ @wraps(fn)
60
+ async def async_wrapped(*args: Any, **kwargs: Any) -> Any:
61
+ return check(await fn(*args, **kwargs))
62
+
63
+ return async_wrapped
64
+
65
+ @wraps(fn)
66
+ def synced(*args: Any, **kwargs: Any) -> Any:
67
+ return check(fn(*args, **kwargs))
68
+
69
+ return synced
70
+
71
+
72
+ def return_annotation(fn: Callable[..., Any]) -> Any:
73
+ """Resolve *fn*'s return annotation, preferring ``get_type_hints``."""
74
+ try:
75
+ hints = get_type_hints(fn)
76
+ except (TypeError, NameError, ValueError):
77
+ hints = {}
78
+ if 'return' in hints:
79
+ return hints['return']
80
+ return inspect.signature(fn).return_annotation
81
+
82
+
83
+ def annotation_matches(annotation: Any, expected: type | tuple[type, ...]) -> bool:
84
+ """Return True when *annotation* is one of *expected* (including ``None``)."""
85
+ expected_types = expected if isinstance(expected, tuple) else (expected,)
86
+ if annotation in expected_types:
87
+ return True
88
+ return expected_types == (type(None),) and annotation in (None, type(None))
89
+
90
+
91
+ def stamp_task_kwargs(
92
+ kwargs: dict[str, Any],
93
+ task: AgentTask | str,
94
+ extra: dict[str, Any] | None = None,
95
+ ) -> dict[str, Any]:
96
+ """Copy decorator kwargs and stamp task tags plus ``_meta.mcp_server``."""
97
+ value = task.value if isinstance(task, AgentTask) else task
98
+ stamped = dict(kwargs)
99
+ tags = set(stamped.get('tags') or set())
100
+ tags.add(value)
101
+ stamped['tags'] = tags
102
+ meta = dict(stamped.get('meta') or {})
103
+ payload = dict(meta.get(META_NAMESPACE) or {})
104
+ payload['task'] = value
105
+ if extra:
106
+ payload.update(extra)
107
+ meta[META_NAMESPACE] = payload
108
+ stamped['meta'] = meta
109
+ return stamped
110
+
111
+
112
+ def task_from_meta(
113
+ meta: dict[str, Any] | None,
114
+ tags: Iterable[str] | None = None,
115
+ ) -> AgentTask:
116
+ """Read the agent task from MCP tool meta, then FastMCP tags, else completion."""
117
+ if meta:
118
+ payload = meta.get(META_NAMESPACE)
119
+ if isinstance(payload, dict):
120
+ raw_task = payload.get('task')
121
+ if isinstance(raw_task, str):
122
+ if raw_task in AGENT_TASK_VALUES:
123
+ return AgentTask(raw_task)
124
+ return AgentTask.NONE
125
+ fastmcp_meta = meta.get('fastmcp')
126
+ if isinstance(fastmcp_meta, dict):
127
+ tag_list = fastmcp_meta.get('tags')
128
+ if isinstance(tag_list, list):
129
+ tagged = _task_from_tags(tag_list)
130
+ if tagged is not None:
131
+ return tagged
132
+ if tags is not None:
133
+ tagged = _task_from_tags(tags)
134
+ if tagged is not None:
135
+ return tagged
136
+ return AgentTask.COMPLETION
137
+
138
+
139
+ def tools_for_task(tools: Sequence[Any], task: AgentTask | str) -> list[Any]:
140
+ """Filter MCP or FastMCP tool objects whose stamped agent task matches *task*."""
141
+ wanted = AgentTask(task)
142
+ return [tool for tool in tools if tool_task(tool) is wanted]
143
+
144
+
145
+ def tool_task(tool: Any) -> AgentTask:
146
+ """Read the agent task from a FastMCP component or MCP SDK Tool."""
147
+ meta = getattr(tool, 'meta', None)
148
+ get_meta = getattr(tool, 'get_meta', None)
149
+ if callable(get_meta):
150
+ resolved = get_meta()
151
+ if isinstance(resolved, dict):
152
+ meta = resolved
153
+ tags = getattr(tool, 'tags', None)
154
+ return task_from_meta(meta if isinstance(meta, dict) else None, tags)
155
+
156
+
157
+ def _task_from_tags(tags: Iterable[str]) -> AgentTask | None:
158
+ for tag in tags:
159
+ if tag in AGENT_TASK_VALUES:
160
+ return AgentTask(tag)
161
+ return None
@@ -0,0 +1,229 @@
1
+ Metadata-Version: 2.5
2
+ Name: brawler-mcp-server-python
3
+ Version: 0.1.0
4
+ Summary: FastMCP wrapper that tags agent task tools for Brawler and other MCP clients.
5
+ Project-URL: Homepage, https://github.com/DanielFloresDiaz/brawler-mcp-server-python
6
+ Project-URL: Source, https://github.com/DanielFloresDiaz/brawler-mcp-server-python
7
+ Project-URL: Documentation, https://github.com/DanielFloresDiaz/brawler-mcp-server-python#readme
8
+ Author-email: Daniel Flores Díaz <danielfloresdiaz17@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: fastmcp<5,>=4.1.1
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Brawler MCP Server (Python)
27
+
28
+ FastMCP wrapper that tags tools with **agent tasks** so a client can list and run context, completion, evaluation, post, and none tools from one MCP server.
29
+
30
+ This is not a fork of [FastMCP](https://github.com/PrefectHQ/fastmcp). It depends on FastMCP 4 and subclasses `FastMCP`. Later language ports (`brawler-mcp-server-typescript`, and so on) should implement the same wire contract.
31
+
32
+ Brawler agents attach one MCP server as a resource, then fetch tools by task: context tools build the prompt, completion tools are offered to the model, post and eval tools run after a result. Native Brawler skills stay on the agent; MCP does not offer a skill task.
33
+
34
+ ---
35
+
36
+ ## What this adds on top of FastMCP
37
+
38
+ | FastMCP | This package |
39
+ | --- | --- |
40
+ | `@mcp.tool` | Same decorator, stamped as **completion** |
41
+ | No task model | `@context_tool`, `@eval_tool`, `@post_tool`, `@none_tool` |
42
+ | Tags are optional | Every task decorator sets a task tag and `_meta.mcp_server` |
43
+ | `tools/list` returns a flat list | Clients filter by `_meta.mcp_server.task` (or call `tools_by_task`) |
44
+
45
+ Untagged tools from a plain FastMCP server are treated as **completion** by Brawler. Tools from this package always carry an explicit task. FastMCP tags that are not agent tasks (for example `skill`, `router`, `training`) are ignored when resolving the task; an unknown ``mcp_server.task`` value is treated as **none**.
46
+
47
+ ---
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ uv add brawler-mcp-server-python
53
+ # or
54
+ pip install brawler-mcp-server-python
55
+ ```
56
+
57
+ Requires Python 3.10+ and FastMCP 4.1.3+.
58
+
59
+ ---
60
+
61
+ ## Quick start
62
+
63
+ ```python
64
+ from brawler_mcp_server import BrawlerMCP
65
+
66
+ mcp = BrawlerMCP('Docs')
67
+
68
+
69
+ @mcp.context_tool
70
+ def policies() -> str:
71
+ """Injected into the agent system prompt."""
72
+ return 'Always cite sources.'
73
+
74
+
75
+ @mcp.context_tool(as_user_message=True)
76
+ def ticket() -> str:
77
+ return 'Ticket #123 is still open.'
78
+
79
+
80
+ @mcp.tool
81
+ def search(q: str) -> str:
82
+ """Completion tool offered to the model."""
83
+ return f'Results for {q}'
84
+
85
+
86
+ @mcp.eval_tool
87
+ def grounded(answer: str) -> tuple[bool, float, str | None]:
88
+ if not answer.strip():
89
+ return False, 0.0, 'Answer is empty.'
90
+ return True, 1.0, None
91
+
92
+
93
+ @mcp.post_tool
94
+ def audit(answer: str) -> None:
95
+ return None
96
+
97
+
98
+ @mcp.none_tool
99
+ def ping() -> str:
100
+ """Visible to generic MCP clients; Brawler agents ignore none tools."""
101
+ return 'pong'
102
+
103
+
104
+ if __name__ == '__main__':
105
+ mcp.run()
106
+ ```
107
+
108
+ `mcp.run()` speaks stdio by default. Use FastMCP HTTP transports when you need a remote endpoint.
109
+
110
+ Example server shipped in ``examples/``:
111
+
112
+ ```bash
113
+ uv run brawler-mcp-example
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Wire contract
119
+
120
+ MCP `tools/list` has no task filter. Identity lives on each tool so any language client can list a subset after listing.
121
+
122
+ ```json
123
+ {
124
+ "name": "policies",
125
+ "description": "Injected into the agent system prompt.",
126
+ "_meta": {
127
+ "mcp_server": {
128
+ "task": "context",
129
+ "as_user_message": false
130
+ },
131
+ "fastmcp": {
132
+ "tags": ["context"]
133
+ }
134
+ }
135
+ }
136
+ ```
137
+
138
+ ### `_meta.mcp_server`
139
+
140
+ | Field | Type | When |
141
+ | --- | --- | --- |
142
+ | `task` | `context` \| `completion` \| `evaluation` \| `post_tool` \| `none` | Always |
143
+ | `as_user_message` | `bool` | Context only. `true` injects the string as a user message instead of the system prompt. |
144
+
145
+ FastMCP also copies the task into `_meta.fastmcp.tags`. Clients may use either field. If both are missing, treat the tool as `completion`. If `task` is set to an unsupported value, treat the tool as `none`.
146
+
147
+ ### Listing only context tools
148
+
149
+ ```python
150
+ from fastmcp import Client
151
+ from brawler_mcp_server import tools_for_task
152
+
153
+ async with Client(mcp) as client:
154
+ tools = await client.list_tools()
155
+ context_tools = tools_for_task(tools, 'context')
156
+ ```
157
+
158
+ In-process (no MCP round-trip):
159
+
160
+ ```python
161
+ context_tools = await mcp.tools_by_task('context')
162
+ ```
163
+
164
+ ---
165
+
166
+ ## Return types
167
+
168
+ | Decorator | Python return | On the wire |
169
+ | --- | --- | --- |
170
+ | `@context_tool` | `str` | Single text content |
171
+ | `@eval_tool` | `tuple[bool, float, str \| None]` | JSON `{"is_valid": bool, "score": float, "feedback": str \| null}` |
172
+ | `@post_tool` | `None` | Empty / ignored text |
173
+ | `@tool` / `@none_tool` | FastMCP default | FastMCP default |
174
+
175
+ Decorators check the annotation at registration time.
176
+
177
+ ---
178
+
179
+ ## Agent tasks (this package)
180
+
181
+ Router, training, and skill are not included. Router and training are not function-tool tasks on a Brawler agent. Skills are native Brawler tools, not MCP tasks.
182
+
183
+ | Task | Decorator | Agent use |
184
+ | --- | --- | --- |
185
+ | `context` | `@context_tool` | Prompt / user-message injection |
186
+ | `completion` | `@tool` | Model-callable tools |
187
+ | `evaluation` | `@eval_tool` | After the final result |
188
+ | `post_tool` | `@post_tool` | Side effects after the result, before eval |
189
+ | `none` | `@none_tool` | Not used by Brawler agents |
190
+
191
+ ---
192
+
193
+ ## Using with Brawler
194
+
195
+ Register the server as an MCP resource on an agent the same way as any other MCP connection (`MCPClient.from_server` / `agent.mcp(...)` / `POST /mcps`). The persisted row stays `entity_type=mcp` with `task=completion` (the connection). Remote tools carry the task in `_meta.mcp_server`.
196
+
197
+ At run time the agent lists tools, keeps completion tools for the model, and calls context / post / eval tools at the matching pipeline stage.
198
+
199
+ ---
200
+
201
+ ## Development
202
+
203
+ ```bash
204
+ uv sync --all-extras --group lint --group dev
205
+ uv run pytest tests/
206
+ make test
207
+ make typecheck
208
+ ```
209
+
210
+ If this repo is checked out as a submodule of brawler, `uv run` still uses this
211
+ package's own environment. Do not run these tests with brawler's FastMCP 3 venv.
212
+
213
+ CI (`.github/workflows/testing.yaml`) runs lint, pyright, and pytest on pull requests to `main`. The release workflow (`.github/workflows/release.yaml`) runs the same tests, builds the package, creates a GitHub release from `changelogs/v<tag>.md`, and publishes to PyPI when a version tag is pushed.
214
+
215
+ ### Releasing
216
+
217
+ 1. Bump `version` in `pyproject.toml`.
218
+ 2. Add `changelogs/v<tag>.md` and update `changelogs/latest.md` to match (tag includes the `v` prefix, e.g. `v0.1.0`).
219
+ 3. Merge to `main`, then tag and push: `git tag v0.1.0 && git push origin v0.1.0`.
220
+
221
+ Before the first PyPI publish, register a **trusted publisher** on [pypi.org](https://pypi.org) for project `brawler-mcp-server-python`: owner `DanielFloresDiaz`, repository `brawler-mcp-server-python`, workflow name `release.yaml`, environment blank. No API token secret is required.
222
+
223
+ After merging workflow changes, smoke-test locally with `uv build` and inspect `dist/`, then confirm the tag workflow uploads GitHub release assets and the new version appears on PyPI.
224
+
225
+ ---
226
+
227
+ ## License
228
+
229
+ Apache-2.0
@@ -0,0 +1,18 @@
1
+ brawler_mcp_server/__init__.py,sha256=wqiONerd3p6ocF6oeSI7A05F0ldEOoYBubJnTNh1PIo,329
2
+ brawler_mcp_server/server.py,sha256=jh0Dakq9-7tZf73UONOQfmbHfa9cbkclukNE3_b2-uo,4287
3
+ brawler_mcp_server/testkit.py,sha256=GGd0KuKKnVEZWbhWVNRKAPr7ahSE22wd-xdi9oYHjTw,2252
4
+ brawler_mcp_server/utils.py,sha256=tmGjvMoTbZ5BGVf0Bu3GrizfE-wfP8sq8aVXGym8Cr4,5413
5
+ brawler_mcp_server/tasks/__init__.py,sha256=ZB4O96IXtZVVFIIhShLi-ywKQkJ1fTws5_r4nSCe9zc,500
6
+ brawler_mcp_server/tasks/completion.py,sha256=iva9p30IWPdgWPBbZTrpIAJ6Y0X4JvgpZjGd65k4gE0,347
7
+ brawler_mcp_server/tasks/context.py,sha256=63IU2u7J_Rj19cbYbfjxqPRf0WEvnUJSfmKZQlA2M_w,1117
8
+ brawler_mcp_server/tasks/evaluation.py,sha256=vg0KN04lP8fd8NZxEFTI6P0-awgTChZQY9FnHsVfXPw,2992
9
+ brawler_mcp_server/tasks/none.py,sha256=6SQbYn5GE3wf7Js-dLYbNK-CSEZ7cORKUTJW9XFiE6M,312
10
+ brawler_mcp_server/tasks/post.py,sha256=befhjztw3lMZmU-eDp0Nswj4WAPa5XTXiKK4dA4mZAE,888
11
+ examples/__init__.py,sha256=XbUnXEsT4S9erJrG_u4lwpRajwgN-WJiRVb7yKPe-mY,44
12
+ examples/example.py,sha256=FSnYmKATfaJTVSpyowFU5aCNuOohoMFeFzcb26apFD8,1190
13
+ examples/task_server.py,sha256=ZqVJBcSHKie8LgLaLCBon1SjTioy2_iBYZ8-JsnlJV4,4450
14
+ brawler_mcp_server_python-0.1.0.dist-info/METADATA,sha256=N9COnB1TKD4nq19oKxdbOEMHaXT-bbmp_9skCFJJJDM,7832
15
+ brawler_mcp_server_python-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
16
+ brawler_mcp_server_python-0.1.0.dist-info/entry_points.txt,sha256=DD4dggxB1kvYPFxdkDd1X-7dMfLy4dmTJh2XHgjoAZs,114
17
+ brawler_mcp_server_python-0.1.0.dist-info/licenses/LICENSE,sha256=VTizCijyEqDndSBoZc5qmvYz0LtSNq-ZGW5HQw0PH9o,11349
18
+ brawler_mcp_server_python-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ brawler-mcp-example = examples.example:main
3
+ brawler-mcp-task-server = examples.task_server:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Daniel Flores Díaz
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
examples/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Example MCP servers for this package."""
examples/example.py ADDED
@@ -0,0 +1,54 @@
1
+ """Example stdio server used by package tests and Brawler integration tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from brawler_mcp_server.server import BrawlerMCP
6
+
7
+ mcp = BrawlerMCP('BrawlerExample')
8
+
9
+
10
+ @mcp.context_tool
11
+ def policies() -> str:
12
+ """Company policy injected into the agent system prompt."""
13
+ return 'Always cite sources.'
14
+
15
+
16
+ @mcp.context_tool(as_user_message=True)
17
+ def open_ticket() -> str:
18
+ """Ticket reminder injected as a user message."""
19
+ return 'Ticket #123 is still open.'
20
+
21
+
22
+ @mcp.tool
23
+ def echo(text: str) -> str:
24
+ """Echo the given text back to the model."""
25
+ return text
26
+
27
+
28
+ @mcp.eval_tool
29
+ def grounded(answer: str) -> tuple[bool, float, str | None]:
30
+ """Reject empty answers."""
31
+ if not str(answer).strip():
32
+ return False, 0.0, 'Answer is empty.'
33
+ return True, 1.0, None
34
+
35
+
36
+ @mcp.post_tool
37
+ def audit(answer: str) -> None:
38
+ """No-op post tool used to verify post-task listing and calls."""
39
+ return
40
+
41
+
42
+ @mcp.none_tool
43
+ def ping() -> str:
44
+ """Generic MCP ping; Brawler agents skip none tools."""
45
+ return 'pong'
46
+
47
+
48
+ def main() -> None:
49
+ """Run the example server over stdio."""
50
+ mcp.run()
51
+
52
+
53
+ if __name__ == '__main__':
54
+ main()
@@ -0,0 +1,170 @@
1
+ """Stdio MCP server used by Brawler's real-env MCPTool tests.
2
+
3
+ Registers at least one tool per agent task, plus untagged / unsupported tools so
4
+ the client can exercise task detection from ``_meta`` and FastMCP tags.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import TypedDict
11
+
12
+ from fastmcp import FastMCP
13
+
14
+ from brawler_mcp_server.server import BrawlerMCP
15
+
16
+
17
+ class AddResult(TypedDict):
18
+ """Structured sum returned by the ``add`` completion tool."""
19
+
20
+ sum: int
21
+
22
+
23
+ mcp = BrawlerMCP('BrawlerTaskServer')
24
+
25
+
26
+ @mcp.context_tool
27
+ def policies() -> str:
28
+ """Company policy injected into the agent system prompt."""
29
+ return 'Always cite sources.'
30
+
31
+
32
+ @mcp.context_tool(as_user_message=True)
33
+ def open_ticket() -> str:
34
+ """Ticket reminder injected as a user message."""
35
+ return 'Ticket #123 is still open.'
36
+
37
+
38
+ @mcp.context_tool
39
+ def locale(language: str) -> str:
40
+ """Locale hint that takes a language code."""
41
+ return f'Reply in {language}.'
42
+
43
+
44
+ @mcp.context_tool
45
+ def boom() -> str:
46
+ """Context tool that fails so the client can observe a swallowed error."""
47
+ raise RuntimeError('context failed')
48
+
49
+
50
+ @mcp.tool
51
+ def echo(text: str) -> str:
52
+ """Echo the given text back to the model."""
53
+ return text
54
+
55
+
56
+ @mcp.tool
57
+ def add(a: int, b: int) -> AddResult:
58
+ """Add two integers and return structured output."""
59
+ return {'sum': a + b}
60
+
61
+
62
+ @mcp.tool
63
+ def fail(text: str) -> str:
64
+ """Completion tool that raises so run_tool_call can observe a remote error."""
65
+ raise RuntimeError(f'remote failed: {text}')
66
+
67
+
68
+ @mcp.eval_tool
69
+ def grounded(answer: str) -> tuple[bool, float, str | None]:
70
+ """Reject empty answers."""
71
+ if not str(answer).strip():
72
+ return False, 0.0, 'Answer is empty.'
73
+ return True, 1.0, None
74
+
75
+
76
+ @mcp.eval_tool
77
+ def score_length(answer: str) -> tuple[bool, float, str | None]:
78
+ """Score a non-empty answer by character length."""
79
+ stripped = str(answer).strip()
80
+ if len(stripped) < 3:
81
+ return False, 0.25, 'Answer is too short.'
82
+ return True, 0.9, 'ok'
83
+
84
+
85
+ @mcp.post_tool
86
+ def audit(answer: str) -> None:
87
+ """No-op post tool used to verify post-task listing and calls."""
88
+ return
89
+
90
+
91
+ @mcp.post_tool
92
+ def record(value: int, query: str) -> None:
93
+ """Post tool with multiple input fields."""
94
+ return
95
+
96
+
97
+ @mcp.none_tool
98
+ def ping() -> str:
99
+ """Generic MCP ping; Brawler agents skip none tools."""
100
+ return 'pong'
101
+
102
+
103
+ def legacy_search(q: str) -> str:
104
+ """Untagged FastMCP tool; Brawler treats it as completion."""
105
+ return f'results for {q}'
106
+
107
+
108
+ def style() -> str:
109
+ """Skill-tagged tool; Brawler treats unsupported tasks as none."""
110
+ return 'Prefer short sentences.'
111
+
112
+
113
+ def route(query: str) -> str:
114
+ """Router-tagged tool; Brawler treats unsupported tasks as none."""
115
+ return 'routed'
116
+
117
+
118
+ def train() -> str:
119
+ """Training-tagged tool; Brawler treats unsupported tasks as none."""
120
+ return 'train'
121
+
122
+
123
+ def unknown_task(q: str) -> str:
124
+ """``mcp_server.task`` that is not a Task value defaults to completion."""
125
+ return f'unknown:{q}'
126
+
127
+
128
+ def tagged_eval(answer: str) -> str:
129
+ """Evaluation via FastMCP tags only (no ``mcp_server.task``)."""
130
+ return json.dumps({'is_valid': True, 'score': 1.0, 'feedback': None})
131
+
132
+
133
+ def broken_eval(answer: str) -> str:
134
+ """Evaluation tool that returns non-object text."""
135
+ return 'not-json'
136
+
137
+
138
+ def valid_no_score(answer: str) -> str:
139
+ """Evaluation tool that omits ``score`` so the client can default it."""
140
+ return json.dumps({'is_valid': True, 'feedback': 'fine'})
141
+
142
+
143
+ def _plain_tool(
144
+ fn: object,
145
+ *,
146
+ name: str,
147
+ tags: set[str] | None = None,
148
+ meta: dict[str, object] | None = None,
149
+ ) -> None:
150
+ """Register a FastMCP tool without BrawlerMCP's task stamp."""
151
+ FastMCP.tool(mcp, name=name, tags=tags, meta=meta)(fn)
152
+
153
+
154
+ _plain_tool(legacy_search, name='legacy_search')
155
+ _plain_tool(style, name='style', tags={'skill'})
156
+ _plain_tool(route, name='route', tags={'router'})
157
+ _plain_tool(train, name='train', tags={'training'})
158
+ _plain_tool(unknown_task, name='unknown_task', meta={'mcp_server': {'task': 'not-a-task'}})
159
+ _plain_tool(tagged_eval, name='tagged_eval', tags={'evaluation'})
160
+ _plain_tool(broken_eval, name='broken_eval', meta={'mcp_server': {'task': 'evaluation'}})
161
+ _plain_tool(valid_no_score, name='valid_no_score', meta={'mcp_server': {'task': 'evaluation'}})
162
+
163
+
164
+ def main() -> None:
165
+ """Run the task server over stdio."""
166
+ mcp.run()
167
+
168
+
169
+ if __name__ == '__main__':
170
+ main()