ado-mcp-server 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.
- ado_mcp/__init__.py +6 -0
- ado_mcp/__main__.py +6 -0
- ado_mcp/_version.py +9 -0
- ado_mcp/ado_mcp.py +64 -0
- ado_mcp/cli.py +43 -0
- ado_mcp/client.py +323 -0
- ado_mcp/constants.py +166 -0
- ado_mcp/content_safety.py +106 -0
- ado_mcp/discovery.py +189 -0
- ado_mcp/elicitation.py +268 -0
- ado_mcp/exceptions.py +175 -0
- ado_mcp/operations.py +73 -0
- ado_mcp/settings.py +112 -0
- ado_mcp/tools/__init__.py +1 -0
- ado_mcp/tools/_shared.py +130 -0
- ado_mcp/tools/core.py +237 -0
- ado_mcp/tools/search.py +82 -0
- ado_mcp/tools/work.py +279 -0
- ado_mcp/tools/work_item_writes.py +720 -0
- ado_mcp/tools/work_items.py +490 -0
- ado_mcp/utils.py +112 -0
- ado_mcp_server-0.1.0.dist-info/METADATA +592 -0
- ado_mcp_server-0.1.0.dist-info/RECORD +26 -0
- ado_mcp_server-0.1.0.dist-info/WHEEL +4 -0
- ado_mcp_server-0.1.0.dist-info/entry_points.txt +3 -0
- ado_mcp_server-0.1.0.dist-info/licenses/LICENSE +21 -0
ado_mcp/__init__.py
ADDED
ado_mcp/__main__.py
ADDED
ado_mcp/_version.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"The version module for the ado-mcp package."
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("ado-mcp-server")
|
|
7
|
+
except PackageNotFoundError: # pragma: no cover
|
|
8
|
+
# Fallback for local dev or editable installs
|
|
9
|
+
__version__ = "0.0.0"
|
ado_mcp/ado_mcp.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Server assembly: the FastMCP server, its lifespan, and the transports."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
|
|
5
|
+
from fastmcp import FastMCP
|
|
6
|
+
from fastmcp.server.lifespan import Lifespan, lifespan
|
|
7
|
+
|
|
8
|
+
from ._version import __version__
|
|
9
|
+
from .client import AdoClient
|
|
10
|
+
from .constants import CLIENT_KEY, HTTP_HOST, HTTP_PATH, SERVER_NAME, SETTINGS_KEY
|
|
11
|
+
from .content_safety import ResponseBoundaryMiddleware
|
|
12
|
+
from .settings import Settings
|
|
13
|
+
from .tools import core, search, work, work_item_writes, work_items
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _lifespan(settings: Settings) -> Lifespan:
|
|
17
|
+
"""Return a lifespan that owns one collection client for the server's lifetime."""
|
|
18
|
+
|
|
19
|
+
@lifespan
|
|
20
|
+
async def client_lifespan(_server: FastMCP) -> AsyncIterator[dict[str, object]]:
|
|
21
|
+
client = AdoClient(settings)
|
|
22
|
+
try:
|
|
23
|
+
yield {CLIENT_KEY: client, SETTINGS_KEY: settings}
|
|
24
|
+
finally:
|
|
25
|
+
await client.aclose()
|
|
26
|
+
|
|
27
|
+
return client_lifespan
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def create_server(settings: Settings) -> FastMCP:
|
|
31
|
+
"""Build the MCP server with every tool registered.
|
|
32
|
+
|
|
33
|
+
Arguments are validated strictly (no `"10"` for a number), and an unexpected
|
|
34
|
+
exception reaches the client only as FastMCP's generic text.
|
|
35
|
+
"""
|
|
36
|
+
mcp = FastMCP(
|
|
37
|
+
SERVER_NAME,
|
|
38
|
+
version=__version__,
|
|
39
|
+
lifespan=_lifespan(settings),
|
|
40
|
+
middleware=[ResponseBoundaryMiddleware()],
|
|
41
|
+
mask_error_details=True,
|
|
42
|
+
strict_input_validation=True,
|
|
43
|
+
)
|
|
44
|
+
for module in (core, work, work_items, search, work_item_writes):
|
|
45
|
+
module.register(mcp)
|
|
46
|
+
return mcp
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def run_server(settings: Settings, *, http: bool, port: int) -> None:
|
|
50
|
+
"""Serve MCP on stdio, or on loopback HTTP at `http://127.0.0.1:{port}/mcp`."""
|
|
51
|
+
mcp = create_server(settings)
|
|
52
|
+
if http:
|
|
53
|
+
# "auto" validates Host and Origin headers on a loopback bind, which
|
|
54
|
+
# blocks web pages that reach the port through DNS rebinding.
|
|
55
|
+
mcp.run(
|
|
56
|
+
transport="http",
|
|
57
|
+
host=HTTP_HOST,
|
|
58
|
+
port=port,
|
|
59
|
+
path=HTTP_PATH,
|
|
60
|
+
host_origin_protection="auto",
|
|
61
|
+
show_banner=False,
|
|
62
|
+
)
|
|
63
|
+
else:
|
|
64
|
+
mcp.run(transport="stdio", show_banner=False)
|
ado_mcp/cli.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"The console script for ado-mcp."
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
|
|
5
|
+
from . import __version__ as _version
|
|
6
|
+
from .ado_mcp import run_server
|
|
7
|
+
from .constants import DEFAULT_HTTP_PORT
|
|
8
|
+
from .exceptions import ConfigurationError
|
|
9
|
+
from .settings import load_settings
|
|
10
|
+
|
|
11
|
+
_MAX_PORT = 65535
|
|
12
|
+
_PORT_WITHOUT_HTTP = "--port requires --http"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@click.command(context_settings={"help_option_names": ["-h", "--help"]})
|
|
16
|
+
@click.option(
|
|
17
|
+
"--http",
|
|
18
|
+
"http",
|
|
19
|
+
is_flag=True,
|
|
20
|
+
help="Serve MCP over HTTP at http://127.0.0.1:PORT/mcp instead of stdio. "
|
|
21
|
+
"The server listens on the loopback address only.",
|
|
22
|
+
)
|
|
23
|
+
@click.option(
|
|
24
|
+
"--port",
|
|
25
|
+
type=click.IntRange(1, _MAX_PORT),
|
|
26
|
+
default=None,
|
|
27
|
+
help=f"Port for --http. Defaults to {DEFAULT_HTTP_PORT}.",
|
|
28
|
+
)
|
|
29
|
+
@click.version_option(_version, "-v", "--version")
|
|
30
|
+
def main(http: bool, port: int | None) -> None:
|
|
31
|
+
"""Python MCP server for on-premises Azure DevOps Server and TFS.
|
|
32
|
+
|
|
33
|
+
Reads ADO_COLLECTION_URL, ADO_PAT, and the optional ADO_PROJECT and ADO_TEAM
|
|
34
|
+
from the environment or a .env file in the current directory, then serves MCP
|
|
35
|
+
on stdio. With --http it serves at http://127.0.0.1:8000/mcp instead.
|
|
36
|
+
"""
|
|
37
|
+
if port is not None and not http:
|
|
38
|
+
raise click.UsageError(_PORT_WITHOUT_HTTP)
|
|
39
|
+
try:
|
|
40
|
+
settings = load_settings()
|
|
41
|
+
except ConfigurationError as error:
|
|
42
|
+
raise click.ClickException(str(error)) from None
|
|
43
|
+
run_server(settings, http=http, port=port or DEFAULT_HTTP_PORT)
|
ado_mcp/client.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""The HTTP client for one Azure DevOps collection. It is the only code that sends requests."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
import httpx2
|
|
9
|
+
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .constants import (
|
|
12
|
+
API_VERSION_PARAM,
|
|
13
|
+
CONNECT_TIMEOUT_SECONDS,
|
|
14
|
+
FIRST_HTTP_ERROR_STATUS,
|
|
15
|
+
MAX_ERROR_MESSAGE_CHARS,
|
|
16
|
+
MAX_RESPONSE_BYTES,
|
|
17
|
+
REQUEST_TIMEOUT_SECONDS,
|
|
18
|
+
SERVER_NAME,
|
|
19
|
+
UNSUPPORTED_VERSION_TYPE_KEYS,
|
|
20
|
+
)
|
|
21
|
+
from .discovery import (
|
|
22
|
+
ResourceLocation,
|
|
23
|
+
expand_route_template,
|
|
24
|
+
negotiate_api_version,
|
|
25
|
+
parse_location,
|
|
26
|
+
)
|
|
27
|
+
from .exceptions import (
|
|
28
|
+
AdoConnectionError,
|
|
29
|
+
AdoHttpError,
|
|
30
|
+
ResponseTooLargeError,
|
|
31
|
+
UnsupportedOnServerError,
|
|
32
|
+
)
|
|
33
|
+
from .operations import Operation
|
|
34
|
+
from .settings import Settings
|
|
35
|
+
from .utils import (
|
|
36
|
+
JsonValue,
|
|
37
|
+
QueryValue,
|
|
38
|
+
build_basic_auth_header,
|
|
39
|
+
build_query,
|
|
40
|
+
encode_path_segment,
|
|
41
|
+
join_collection_url,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
RouteValues = Mapping[str, str | int | None]
|
|
47
|
+
|
|
48
|
+
_DISCOVERY_METHOD = "OPTIONS"
|
|
49
|
+
_DISCOVERY_PATH = "_apis/{area}"
|
|
50
|
+
_NOT_FOUND = 404
|
|
51
|
+
_METHOD_NOT_ALLOWED = 405
|
|
52
|
+
_FIRST_REDIRECT_STATUS = 300
|
|
53
|
+
_REDIRECT_MESSAGE = "The server answered with a redirect, which ado-mcp does not follow."
|
|
54
|
+
_TIMEOUT_MESSAGE = "The request timed out."
|
|
55
|
+
_TRANSPORT_MESSAGE = "Could not connect to the collection."
|
|
56
|
+
_SEND_MESSAGE = "The request could not be sent."
|
|
57
|
+
_NOT_JSON_MESSAGE = "The server answered with a body that is not JSON."
|
|
58
|
+
_NO_ROUTE_MESSAGE = "The collection does not advertise the route that {label} needs."
|
|
59
|
+
_BAD_VERSION_MESSAGE = "The server does not support API version {version} for {label}."
|
|
60
|
+
_TOO_LARGE_MESSAGE = (
|
|
61
|
+
"The reply exceeds {limit} bytes. Lower `top` or `depth`, name fewer fields, "
|
|
62
|
+
"or narrow the query."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class AdoClient:
|
|
67
|
+
"""Sends REST requests to the configured collection with the PAT.
|
|
68
|
+
|
|
69
|
+
Routes and API versions come from per-area discovery (`OPTIONS
|
|
70
|
+
{collection}/_apis/{area}`), cached for the life of the client. Nothing is
|
|
71
|
+
retried: a write is sent once, and so is every read.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
_collection_url: str
|
|
75
|
+
_http: httpx2.AsyncClient
|
|
76
|
+
# Discovered locations per resource area, keyed by lower-cased location ID.
|
|
77
|
+
_locations: dict[str, dict[str, ResourceLocation]]
|
|
78
|
+
|
|
79
|
+
def __init__(self, settings: Settings) -> None:
|
|
80
|
+
self._collection_url = settings.collection_url
|
|
81
|
+
# The Authorization value is built once here and lives only in the
|
|
82
|
+
# client's default headers. Certificate verification and proxy
|
|
83
|
+
# environment variables keep their library defaults (on).
|
|
84
|
+
self._http = httpx2.AsyncClient(
|
|
85
|
+
headers={
|
|
86
|
+
"Authorization": build_basic_auth_header(settings.pat.get_secret_value()),
|
|
87
|
+
"Accept": "application/json",
|
|
88
|
+
"User-Agent": f"{SERVER_NAME}/{__version__}",
|
|
89
|
+
},
|
|
90
|
+
timeout=httpx2.Timeout(REQUEST_TIMEOUT_SECONDS, connect=CONNECT_TIMEOUT_SECONDS),
|
|
91
|
+
follow_redirects=False,
|
|
92
|
+
)
|
|
93
|
+
self._locations = {}
|
|
94
|
+
|
|
95
|
+
async def send(
|
|
96
|
+
self,
|
|
97
|
+
operation: Operation,
|
|
98
|
+
*,
|
|
99
|
+
label: str,
|
|
100
|
+
method: str,
|
|
101
|
+
route_values: RouteValues | None = None,
|
|
102
|
+
query: Mapping[str, QueryValue] | None = None,
|
|
103
|
+
json_body: JsonValue = None,
|
|
104
|
+
content_type: str | None = None,
|
|
105
|
+
headers: Mapping[str, str] | None = None,
|
|
106
|
+
version_override: str | None = None,
|
|
107
|
+
) -> JsonValue:
|
|
108
|
+
"""Send one request and return the parsed JSON reply (`None` for an empty body).
|
|
109
|
+
|
|
110
|
+
`label` names the tool action, for example `wit_work_item.get`, in
|
|
111
|
+
errors and logs.
|
|
112
|
+
"""
|
|
113
|
+
path, version, on_fallback = await self._resolve(
|
|
114
|
+
operation, route_values or {}, version_override, label
|
|
115
|
+
)
|
|
116
|
+
params = build_query(query or {})
|
|
117
|
+
if version is not None:
|
|
118
|
+
params[API_VERSION_PARAM] = version
|
|
119
|
+
return await self._request(
|
|
120
|
+
method,
|
|
121
|
+
join_collection_url(self._collection_url, path),
|
|
122
|
+
label=label,
|
|
123
|
+
params=params,
|
|
124
|
+
json_body=json_body,
|
|
125
|
+
content_type=content_type,
|
|
126
|
+
headers=headers,
|
|
127
|
+
on_fallback=on_fallback,
|
|
128
|
+
version=version,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
async def negotiated_version(
|
|
132
|
+
self, operation: Operation, requested: str, *, label: str
|
|
133
|
+
) -> str | None:
|
|
134
|
+
"""Return the version `send` would use for `requested`, or `None` with no location."""
|
|
135
|
+
if operation.area is None or operation.location_id is None:
|
|
136
|
+
return None
|
|
137
|
+
locations = await self._area_locations(operation.area, label)
|
|
138
|
+
location = locations.get(operation.location_id)
|
|
139
|
+
if location is None:
|
|
140
|
+
return None
|
|
141
|
+
return negotiate_api_version(requested, location)
|
|
142
|
+
|
|
143
|
+
async def aclose(self) -> None:
|
|
144
|
+
"""Close the underlying HTTP connections."""
|
|
145
|
+
await self._http.aclose()
|
|
146
|
+
|
|
147
|
+
async def _resolve(
|
|
148
|
+
self,
|
|
149
|
+
operation: Operation,
|
|
150
|
+
route_values: RouteValues,
|
|
151
|
+
version_override: str | None,
|
|
152
|
+
label: str,
|
|
153
|
+
) -> tuple[str, str | None, bool]:
|
|
154
|
+
"""Return the relative path, the API version, and whether the path is the fixed fallback.
|
|
155
|
+
|
|
156
|
+
The flag is true only when the operation's `fallback_path` is used, so a 404
|
|
157
|
+
or 405 is read as "route absent" only for that fixed route, never for a
|
|
158
|
+
discovered route that happens to expand to the same text.
|
|
159
|
+
"""
|
|
160
|
+
requested = version_override or operation.requested_version
|
|
161
|
+
if operation.area is None or operation.location_id is None or requested is None:
|
|
162
|
+
# A fixed-route operation; every such entry in `operations.py` has a path.
|
|
163
|
+
if operation.fallback_path is None:
|
|
164
|
+
raise UnsupportedOnServerError(_NO_ROUTE_MESSAGE.format(label=label), label=label)
|
|
165
|
+
return operation.fallback_path, operation.fallback_version, True
|
|
166
|
+
locations = await self._area_locations(operation.area, label)
|
|
167
|
+
location = locations.get(operation.location_id)
|
|
168
|
+
if location is not None:
|
|
169
|
+
# `area` and `resource` default to the location's own names.
|
|
170
|
+
values = {"area": location.area, "resource": location.resource_name, **route_values}
|
|
171
|
+
path = expand_route_template(location.route_template, values)
|
|
172
|
+
return path, negotiate_api_version(requested, location), False
|
|
173
|
+
if operation.fallback_path is not None:
|
|
174
|
+
return operation.fallback_path, operation.fallback_version, True
|
|
175
|
+
raise UnsupportedOnServerError(_NO_ROUTE_MESSAGE.format(label=label), label=label)
|
|
176
|
+
|
|
177
|
+
async def _area_locations(self, area: str, label: str) -> dict[str, ResourceLocation]:
|
|
178
|
+
"""Return the discovered locations of a resource area, discovering them on first use.
|
|
179
|
+
|
|
180
|
+
A 404 or an empty reply means "no locations" and is not cached, so a later
|
|
181
|
+
call tries again. Any other failure is raised, so an authentication error
|
|
182
|
+
never looks like an unsupported route. Two concurrent first calls may both
|
|
183
|
+
discover; the results are identical.
|
|
184
|
+
"""
|
|
185
|
+
cached = self._locations.get(area)
|
|
186
|
+
if cached is not None:
|
|
187
|
+
return cached
|
|
188
|
+
path = _DISCOVERY_PATH.format(area=encode_path_segment(area))
|
|
189
|
+
reply = await self._request(
|
|
190
|
+
_DISCOVERY_METHOD,
|
|
191
|
+
join_collection_url(self._collection_url, path),
|
|
192
|
+
label=label,
|
|
193
|
+
params={},
|
|
194
|
+
allow_not_found=True,
|
|
195
|
+
)
|
|
196
|
+
entries = reply.get("value") if isinstance(reply, dict) else None
|
|
197
|
+
if not isinstance(entries, list):
|
|
198
|
+
return {}
|
|
199
|
+
locations = {}
|
|
200
|
+
for entry in entries:
|
|
201
|
+
location = parse_location(entry) if isinstance(entry, dict) else None
|
|
202
|
+
if location is not None:
|
|
203
|
+
locations[location.id] = location
|
|
204
|
+
self._locations[area] = locations
|
|
205
|
+
return locations
|
|
206
|
+
|
|
207
|
+
async def _request(
|
|
208
|
+
self,
|
|
209
|
+
method: str,
|
|
210
|
+
url: str,
|
|
211
|
+
*,
|
|
212
|
+
label: str,
|
|
213
|
+
params: dict[str, str],
|
|
214
|
+
json_body: JsonValue = None,
|
|
215
|
+
content_type: str | None = None,
|
|
216
|
+
headers: Mapping[str, str] | None = None,
|
|
217
|
+
on_fallback: bool = False,
|
|
218
|
+
version: str | None = None,
|
|
219
|
+
allow_not_found: bool = False,
|
|
220
|
+
) -> JsonValue:
|
|
221
|
+
"""Send one request, bound the reply size, and map failures to this project's errors.
|
|
222
|
+
|
|
223
|
+
`allow_not_found` returns `None` for a 404 instead of raising; discovery
|
|
224
|
+
uses it. The query string, headers, and bodies are never logged.
|
|
225
|
+
"""
|
|
226
|
+
path = urlsplit(url).path
|
|
227
|
+
request_headers = dict(headers or {})
|
|
228
|
+
content = None
|
|
229
|
+
if content_type is not None:
|
|
230
|
+
request_headers["Content-Type"] = content_type
|
|
231
|
+
content = json.dumps(json_body)
|
|
232
|
+
try:
|
|
233
|
+
async with self._http.stream(
|
|
234
|
+
method,
|
|
235
|
+
url,
|
|
236
|
+
params=params,
|
|
237
|
+
content=content,
|
|
238
|
+
json=json_body if content is None else None,
|
|
239
|
+
headers=request_headers,
|
|
240
|
+
follow_redirects=False,
|
|
241
|
+
) as response:
|
|
242
|
+
status = response.status_code
|
|
243
|
+
logger.debug("%s %s %s -> %s", label, method, path, status)
|
|
244
|
+
if status == _NOT_FOUND and allow_not_found:
|
|
245
|
+
return None
|
|
246
|
+
body = await self._read_body(response, label=label, status=status)
|
|
247
|
+
except ResponseTooLargeError:
|
|
248
|
+
logger.exception("%s %s %s failed: reply too large", label, method, path)
|
|
249
|
+
raise
|
|
250
|
+
except httpx2.TimeoutException:
|
|
251
|
+
logger.exception("%s %s %s failed: timeout", label, method, path)
|
|
252
|
+
raise AdoConnectionError(_TIMEOUT_MESSAGE, label=label) from None
|
|
253
|
+
except httpx2.TransportError:
|
|
254
|
+
logger.exception("%s %s %s failed: transport", label, method, path)
|
|
255
|
+
raise AdoConnectionError(_TRANSPORT_MESSAGE, label=label) from None
|
|
256
|
+
except (httpx2.HTTPError, httpx2.InvalidURL):
|
|
257
|
+
logger.exception("%s %s %s failed: request not sent", label, method, path)
|
|
258
|
+
raise AdoConnectionError(_SEND_MESSAGE, label=label) from None
|
|
259
|
+
if status >= _FIRST_REDIRECT_STATUS:
|
|
260
|
+
error = self._error_from_response(status, body, label, on_fallback, version)
|
|
261
|
+
logger.error("%s %s %s failed: %s", label, method, path, error.code)
|
|
262
|
+
raise error
|
|
263
|
+
return self._parse_success(body, label=label, status=status)
|
|
264
|
+
|
|
265
|
+
@staticmethod
|
|
266
|
+
async def _read_body(response: httpx2.Response, *, label: str, status: int) -> bytes:
|
|
267
|
+
"""Read the reply body, stopping once it exceeds `MAX_RESPONSE_BYTES`."""
|
|
268
|
+
too_large = _TOO_LARGE_MESSAGE.format(limit=MAX_RESPONSE_BYTES)
|
|
269
|
+
declared = response.headers.get("content-length")
|
|
270
|
+
if declared is not None and declared.isdigit() and int(declared) > MAX_RESPONSE_BYTES:
|
|
271
|
+
raise ResponseTooLargeError(too_large, label=label, status=status)
|
|
272
|
+
chunks = []
|
|
273
|
+
received = 0
|
|
274
|
+
async for chunk in response.aiter_bytes():
|
|
275
|
+
received += len(chunk)
|
|
276
|
+
if received > MAX_RESPONSE_BYTES:
|
|
277
|
+
raise ResponseTooLargeError(too_large, label=label, status=status)
|
|
278
|
+
chunks.append(chunk)
|
|
279
|
+
return b"".join(chunks)
|
|
280
|
+
|
|
281
|
+
@staticmethod
|
|
282
|
+
def _parse_success(body: bytes, *, label: str, status: int) -> JsonValue:
|
|
283
|
+
"""Parse a success reply; an empty body is `None`, a non-JSON body is an error."""
|
|
284
|
+
if not body.strip():
|
|
285
|
+
return None
|
|
286
|
+
try:
|
|
287
|
+
return json.loads(body)
|
|
288
|
+
except ValueError:
|
|
289
|
+
logger.exception("%s reply is not JSON (HTTP %s)", label, status)
|
|
290
|
+
raise AdoHttpError(_NOT_JSON_MESSAGE, label=label, status=status) from None
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def _error_from_response(
|
|
294
|
+
status: int,
|
|
295
|
+
body: bytes,
|
|
296
|
+
label: str,
|
|
297
|
+
on_fallback: bool,
|
|
298
|
+
version: str | None,
|
|
299
|
+
) -> AdoConnectionError | AdoHttpError | UnsupportedOnServerError:
|
|
300
|
+
"""Map a redirect or error reply to the error the caller sees."""
|
|
301
|
+
if status < FIRST_HTTP_ERROR_STATUS:
|
|
302
|
+
# Redirects are never followed, so the PAT never reaches another URL.
|
|
303
|
+
return AdoConnectionError(_REDIRECT_MESSAGE, label=label, status=status)
|
|
304
|
+
try:
|
|
305
|
+
payload = json.loads(body) if body.strip() else None
|
|
306
|
+
except ValueError:
|
|
307
|
+
payload = None
|
|
308
|
+
details = payload if isinstance(payload, dict) else {}
|
|
309
|
+
if details.get("typeKey") in UNSUPPORTED_VERSION_TYPE_KEYS:
|
|
310
|
+
return UnsupportedOnServerError(
|
|
311
|
+
_BAD_VERSION_MESSAGE.format(version=version, label=label),
|
|
312
|
+
label=label,
|
|
313
|
+
status=status,
|
|
314
|
+
)
|
|
315
|
+
if on_fallback and status in (_NOT_FOUND, _METHOD_NOT_ALLOWED):
|
|
316
|
+
# A fixed route has no entity in its path, so 404 or 405 means the
|
|
317
|
+
# route itself is absent on this server.
|
|
318
|
+
return UnsupportedOnServerError(
|
|
319
|
+
_NO_ROUTE_MESSAGE.format(label=label), label=label, status=status
|
|
320
|
+
)
|
|
321
|
+
message = details.get("message")
|
|
322
|
+
text = message[:MAX_ERROR_MESSAGE_CHARS] if isinstance(message, str) else f"HTTP {status}"
|
|
323
|
+
return AdoHttpError(text, label=label, status=status)
|
ado_mcp/constants.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""All constants used in the code base are defined here."""
|
|
2
|
+
|
|
3
|
+
from types import MappingProxyType
|
|
4
|
+
|
|
5
|
+
# Settings
|
|
6
|
+
ENV_PREFIX = "ADO_"
|
|
7
|
+
ENV_FILE_NAME = ".env"
|
|
8
|
+
# Azure DevOps Services (cloud) hosts. The host itself and every subdomain are
|
|
9
|
+
# rejected, because this server only talks to on-premises collections.
|
|
10
|
+
CLOUD_HOST_SUFFIXES = ("dev.azure.com", "visualstudio.com")
|
|
11
|
+
|
|
12
|
+
# Server and transports
|
|
13
|
+
SERVER_NAME = "ado-mcp"
|
|
14
|
+
# Keys of the lifespan context that tools read the client and settings from.
|
|
15
|
+
CLIENT_KEY = "client"
|
|
16
|
+
SETTINGS_KEY = "settings"
|
|
17
|
+
HTTP_HOST = "127.0.0.1"
|
|
18
|
+
DEFAULT_HTTP_PORT = 8000
|
|
19
|
+
HTTP_PATH = "/mcp"
|
|
20
|
+
|
|
21
|
+
# Limits
|
|
22
|
+
MAX_PAGE_SIZE = 200
|
|
23
|
+
MAX_RESPONSE_BYTES = 2 * 1024 * 1024
|
|
24
|
+
MAX_ERROR_MESSAGE_CHARS = 1000
|
|
25
|
+
MAX_CHILD_ITEMS = 50
|
|
26
|
+
MAX_WIQL_LENGTH = 32768
|
|
27
|
+
ELICITATION_PROJECT_LIMIT = 100
|
|
28
|
+
DEFAULT_PAGE_SIZE = 50
|
|
29
|
+
DEFAULT_SEARCH_PAGE_SIZE = 10
|
|
30
|
+
DEFAULT_ITERATION_DEPTH = 2
|
|
31
|
+
REQUEST_TIMEOUT_SECONDS = 60.0
|
|
32
|
+
CONNECT_TIMEOUT_SECONDS = 10.0
|
|
33
|
+
|
|
34
|
+
# REST conventions
|
|
35
|
+
API_VERSION_PARAM = "api-version"
|
|
36
|
+
BATCH_API_VERSION = "5.0"
|
|
37
|
+
MARKDOWN_COMMENTS_API_VERSION = "7.2-preview.4"
|
|
38
|
+
DIRECT_CALL_API_VERSION = "7.2-preview.1"
|
|
39
|
+
JSON_PATCH_CONTENT_TYPE = "application/json-patch+json"
|
|
40
|
+
READ_CONSISTENCY_HEADER = ("X-VSS-ReadConsistencyLevel", "Eventual")
|
|
41
|
+
# Text formats accepted by work-item fields and comments.
|
|
42
|
+
MARKDOWN_FORMAT = "Markdown"
|
|
43
|
+
HTML_FORMAT = "Html"
|
|
44
|
+
# Numeric values of the comment API's `format` query parameter.
|
|
45
|
+
COMMENT_FORMAT_CODES = MappingProxyType({MARKDOWN_FORMAT: 0, HTML_FORMAT: 1})
|
|
46
|
+
# Relative REST path of a work item, used in relation URLs.
|
|
47
|
+
WORK_ITEM_URL_PATH = "{project}/_apis/wit/workItems/{id}"
|
|
48
|
+
|
|
49
|
+
# Tool annotation sets, matching upstream `src/shared/tool-annotations.ts`.
|
|
50
|
+
READ_ONLY_ANNOTATIONS = MappingProxyType(
|
|
51
|
+
{
|
|
52
|
+
"readOnlyHint": True,
|
|
53
|
+
"destructiveHint": False,
|
|
54
|
+
"idempotentHint": True,
|
|
55
|
+
"openWorldHint": True,
|
|
56
|
+
}
|
|
57
|
+
)
|
|
58
|
+
MUTATING_ANNOTATIONS = MappingProxyType(
|
|
59
|
+
{
|
|
60
|
+
"readOnlyHint": False,
|
|
61
|
+
"destructiveHint": True,
|
|
62
|
+
"idempotentHint": False,
|
|
63
|
+
"openWorldHint": True,
|
|
64
|
+
}
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# Tool names
|
|
68
|
+
CORE_LIST_PROJECTS = "core_list_projects"
|
|
69
|
+
CORE_LIST_PROJECT_TEAMS = "core_list_project_teams"
|
|
70
|
+
CORE_GET_IDENTITY_IDS = "core_get_identity_ids"
|
|
71
|
+
CORE_GET_CURRENT_USER = "core_get_current_user"
|
|
72
|
+
WORK = "work"
|
|
73
|
+
WIT_WORK_ITEM = "wit_work_item"
|
|
74
|
+
WIT_QUERY = "wit_query"
|
|
75
|
+
WIT_BACKLOG = "wit_backlog"
|
|
76
|
+
SEARCH_WORKITEM = "search_workitem"
|
|
77
|
+
WIT_WORK_ITEM_WRITE = "wit_work_item_write"
|
|
78
|
+
WIT_WORK_ITEM_COMMENT_WRITE = "wit_work_item_comment_write"
|
|
79
|
+
WIT_WORK_ITEM_LINK_WRITE = "wit_work_item_link_write"
|
|
80
|
+
|
|
81
|
+
# Domain of each tool, used for the untrusted-content source label
|
|
82
|
+
# ("Azure DevOps {domain}").
|
|
83
|
+
TOOL_DOMAINS = MappingProxyType(
|
|
84
|
+
{
|
|
85
|
+
CORE_LIST_PROJECTS: "core",
|
|
86
|
+
CORE_LIST_PROJECT_TEAMS: "core",
|
|
87
|
+
CORE_GET_IDENTITY_IDS: "core",
|
|
88
|
+
CORE_GET_CURRENT_USER: "core",
|
|
89
|
+
WORK: "work",
|
|
90
|
+
WIT_WORK_ITEM: "work-items",
|
|
91
|
+
WIT_QUERY: "work-items",
|
|
92
|
+
WIT_BACKLOG: "work-items",
|
|
93
|
+
WIT_WORK_ITEM_WRITE: "work-items",
|
|
94
|
+
WIT_WORK_ITEM_COMMENT_WRITE: "work-items",
|
|
95
|
+
WIT_WORK_ITEM_LINK_WRITE: "work-items",
|
|
96
|
+
SEARCH_WORKITEM: "search",
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
# Source labels that upstream sets explicitly, keyed by (tool, action).
|
|
100
|
+
SOURCE_LABEL_OVERRIDES: MappingProxyType[tuple[str, str | None], str] = MappingProxyType(
|
|
101
|
+
{
|
|
102
|
+
(WIT_QUERY, "wiql"): "wiql query results",
|
|
103
|
+
(SEARCH_WORKITEM, None): "work item search results",
|
|
104
|
+
}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# Work-item link type names and their relation types.
|
|
108
|
+
LINK_TYPES = MappingProxyType(
|
|
109
|
+
{
|
|
110
|
+
"parent": "System.LinkTypes.Hierarchy-Reverse",
|
|
111
|
+
"child": "System.LinkTypes.Hierarchy-Forward",
|
|
112
|
+
"duplicate": "System.LinkTypes.Duplicate-Forward",
|
|
113
|
+
"duplicate of": "System.LinkTypes.Duplicate-Reverse",
|
|
114
|
+
"related": "System.LinkTypes.Related",
|
|
115
|
+
"successor": "System.LinkTypes.Dependency-Forward",
|
|
116
|
+
"predecessor": "System.LinkTypes.Dependency-Reverse",
|
|
117
|
+
"tested by": "Microsoft.VSTS.Common.TestedBy-Forward",
|
|
118
|
+
"tests": "Microsoft.VSTS.Common.TestedBy-Reverse",
|
|
119
|
+
"affects": "Microsoft.VSTS.Common.Affects-Forward",
|
|
120
|
+
"affected by": "Microsoft.VSTS.Common.Affects-Reverse",
|
|
121
|
+
"artifact": "ArtifactLink",
|
|
122
|
+
"hyperlink": "Hyperlink",
|
|
123
|
+
}
|
|
124
|
+
)
|
|
125
|
+
HYPERLINK_TYPE = "hyperlink"
|
|
126
|
+
PARENT_RELATION = LINK_TYPES["parent"]
|
|
127
|
+
|
|
128
|
+
# Work-item fields
|
|
129
|
+
DEFAULT_BATCH_FIELDS = (
|
|
130
|
+
"System.Id",
|
|
131
|
+
"System.WorkItemType",
|
|
132
|
+
"System.Title",
|
|
133
|
+
"System.State",
|
|
134
|
+
"System.Parent",
|
|
135
|
+
"System.Tags",
|
|
136
|
+
"Microsoft.VSTS.Common.StackRank",
|
|
137
|
+
"System.AssignedTo",
|
|
138
|
+
)
|
|
139
|
+
IDENTITY_FIELDS = (
|
|
140
|
+
"System.AssignedTo",
|
|
141
|
+
"System.CreatedBy",
|
|
142
|
+
"System.ChangedBy",
|
|
143
|
+
"System.AuthorizedAs",
|
|
144
|
+
"Microsoft.VSTS.Common.ActivatedBy",
|
|
145
|
+
"Microsoft.VSTS.Common.ResolvedBy",
|
|
146
|
+
"Microsoft.VSTS.Common.ClosedBy",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Errors
|
|
150
|
+
HTTP_ERROR_CODES = MappingProxyType(
|
|
151
|
+
{
|
|
152
|
+
401: "authentication_failed",
|
|
153
|
+
403: "permission_denied",
|
|
154
|
+
404: "not_found",
|
|
155
|
+
409: "conflict",
|
|
156
|
+
412: "precondition_failed",
|
|
157
|
+
}
|
|
158
|
+
)
|
|
159
|
+
DEFAULT_HTTP_ERROR_CODE = "request_failed"
|
|
160
|
+
# Code for a success reply whose body is not JSON.
|
|
161
|
+
INVALID_RESPONSE_CODE = "invalid_response"
|
|
162
|
+
FIRST_HTTP_ERROR_STATUS = 400
|
|
163
|
+
# `typeKey` values of the server's "API version not supported" error replies.
|
|
164
|
+
UNSUPPORTED_VERSION_TYPE_KEYS = frozenset(
|
|
165
|
+
{"VssVersionOutOfRangeException", "VssInvalidPreviewVersionException"}
|
|
166
|
+
)
|