managed-deepagents 0.10.2.dev6__py3-none-win_amd64.whl → 0.10.2.dev8__py3-none-win_amd64.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.
- managed_deepagents/_binaries/mda.exe +0 -0
- managed_deepagents/_connection_authorization.py +42 -7
- managed_deepagents/_connectors/mcp/__init__.py +14 -0
- managed_deepagents/_connectors/mcp/load.py +266 -38
- managed_deepagents/_credential_gate.py +229 -9
- {managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/METADATA +10 -1
- {managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/RECORD +11 -11
- {managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/WHEEL +0 -0
- {managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/entry_points.txt +0 -0
- {managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/licenses/LICENSE +0 -0
- {managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/top_level.txt +0 -0
|
Binary file
|
|
@@ -25,6 +25,15 @@ class PendingCredential(TypedDict, total=False):
|
|
|
25
25
|
provider: str
|
|
26
26
|
|
|
27
27
|
|
|
28
|
+
#: Tool metadata key naming the credential a tool needs before its first call.
|
|
29
|
+
CONNECT_ON_USE_METADATA = "mda_connect_on_use"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ConnectOnUse(TypedDict):
|
|
33
|
+
server: str
|
|
34
|
+
credential: PendingCredential
|
|
35
|
+
|
|
36
|
+
|
|
28
37
|
class CredentialAuthorizationRequiredInterrupt(TypedDict):
|
|
29
38
|
"""Interrupt payload when the caller has not granted one or more connections."""
|
|
30
39
|
|
|
@@ -42,6 +51,33 @@ class _UserConnectionGrant:
|
|
|
42
51
|
|
|
43
52
|
InterruptFn = Callable[[CredentialAuthorizationRequiredInterrupt], None]
|
|
44
53
|
|
|
54
|
+
DEFAULT_AUTHORIZATION_MESSAGE = "Connect the following integrations to continue."
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ToolCredentialRequiredError(Exception):
|
|
58
|
+
"""A tool call was refused until the caller connects its credentials.
|
|
59
|
+
|
|
60
|
+
``credentials`` is empty when the refusal carried no link to connect from.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, provider: str, credentials: Sequence[PendingCredential]) -> None:
|
|
64
|
+
super().__init__(f"{provider} is not connected")
|
|
65
|
+
self.provider = provider
|
|
66
|
+
self.credentials = list(credentials)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def credential_authorization_interrupt(
|
|
70
|
+
credentials: Sequence[PendingCredential],
|
|
71
|
+
message: str = DEFAULT_AUTHORIZATION_MESSAGE,
|
|
72
|
+
) -> CredentialAuthorizationRequiredInterrupt:
|
|
73
|
+
"""The interrupt payload that asks the caller to connect ``credentials``."""
|
|
74
|
+
return {
|
|
75
|
+
"type": "credential_authorization_required",
|
|
76
|
+
"message": message,
|
|
77
|
+
"credentials": list(credentials),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
45
81
|
_defer_interrupts: ContextVar[bool] = ContextVar("mda_defer_credential_interrupts", default=False)
|
|
46
82
|
|
|
47
83
|
|
|
@@ -62,7 +98,7 @@ def raise_credential_authorization_required(
|
|
|
62
98
|
credentials: Sequence[PendingCredential],
|
|
63
99
|
*,
|
|
64
100
|
interrupt: InterruptFn | None = None,
|
|
65
|
-
message: str =
|
|
101
|
+
message: str = DEFAULT_AUTHORIZATION_MESSAGE,
|
|
66
102
|
) -> None:
|
|
67
103
|
"""Interrupt once with the given missing credentials, then raise.
|
|
68
104
|
|
|
@@ -73,12 +109,7 @@ def raise_credential_authorization_required(
|
|
|
73
109
|
raise ValueError("credentials must be non-empty")
|
|
74
110
|
if _defer_interrupts.get():
|
|
75
111
|
raise CredentialAuthorizationDeferredError(credentials)
|
|
76
|
-
|
|
77
|
-
"type": "credential_authorization_required",
|
|
78
|
-
"message": message,
|
|
79
|
-
"credentials": list(credentials),
|
|
80
|
-
}
|
|
81
|
-
(interrupt or _interrupt)(payload)
|
|
112
|
+
(interrupt or _interrupt)(credential_authorization_interrupt(credentials, message))
|
|
82
113
|
raise CredentialAuthorizationRequiredError(
|
|
83
114
|
[str(credential["slug"]) for credential in credentials]
|
|
84
115
|
)
|
|
@@ -145,10 +176,14 @@ def _interrupt(payload: CredentialAuthorizationRequiredInterrupt) -> None:
|
|
|
145
176
|
|
|
146
177
|
|
|
147
178
|
__all__ = [
|
|
179
|
+
"CONNECT_ON_USE_METADATA",
|
|
180
|
+
"ConnectOnUse",
|
|
148
181
|
"CredentialAuthorizationDeferredError",
|
|
149
182
|
"CredentialAuthorizationRequiredInterrupt",
|
|
150
183
|
"PendingCredential",
|
|
184
|
+
"ToolCredentialRequiredError",
|
|
151
185
|
"collect_pending_user_connection_credentials",
|
|
186
|
+
"credential_authorization_interrupt",
|
|
152
187
|
"defer_credential_interrupts",
|
|
153
188
|
"raise_credential_authorization_required",
|
|
154
189
|
"resolve_user_connection_grants",
|
|
@@ -151,6 +151,16 @@ class McpServersConfig(TypedDict, closed=True):
|
|
|
151
151
|
teardown.
|
|
152
152
|
"""
|
|
153
153
|
|
|
154
|
+
jit_auth: NotRequired[bool]
|
|
155
|
+
"""Optional, default False. Ask for LangSmith managed-tools connections on use.
|
|
156
|
+
|
|
157
|
+
Applies only to LangSmith managed-tools URLs. When True, a kit's tools for
|
|
158
|
+
providers the caller has not connected are still offered to the model; the
|
|
159
|
+
first call to one interrupts with the connect link and retries that call
|
|
160
|
+
after the run resumes. By default the run asks for every missing connection
|
|
161
|
+
before it starts.
|
|
162
|
+
"""
|
|
163
|
+
|
|
154
164
|
|
|
155
165
|
__all__ = [
|
|
156
166
|
"HttpMcpServerConfig",
|
|
@@ -390,6 +400,7 @@ class _McpServersArgs(BaseModel):
|
|
|
390
400
|
servers: dict[str, _RemoteMcpServer]
|
|
391
401
|
throw_on_load_error: StrictBool = True
|
|
392
402
|
on_connection_error: str = "throw"
|
|
403
|
+
jit_auth: StrictBool = False
|
|
393
404
|
|
|
394
405
|
@model_validator(mode="before")
|
|
395
406
|
@classmethod
|
|
@@ -438,6 +449,9 @@ def define_mcp(**config: Unpack[McpServersConfig]) -> McpServersDefinition:
|
|
|
438
449
|
requirements and invalid selections always surface.
|
|
439
450
|
on_connection_error: Default and only value ``"throw"``. Native invocation
|
|
440
451
|
failures propagate; native MCP tool errors retain failed tool output.
|
|
452
|
+
jit_auth: Default False. True asks for a LangSmith managed-tools
|
|
453
|
+
connection when the model first calls one of its tools, instead of
|
|
454
|
+
before the run starts.
|
|
441
455
|
|
|
442
456
|
Returns:
|
|
443
457
|
A ``McpServersDefinition`` consumed by the managed runtime.
|
|
@@ -8,13 +8,15 @@ import json
|
|
|
8
8
|
import os
|
|
9
9
|
import threading
|
|
10
10
|
import warnings
|
|
11
|
-
from collections.abc import AsyncGenerator, Awaitable, Callable, Mapping, Sequence
|
|
11
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Collection, Mapping, Sequence
|
|
12
12
|
from functools import partial
|
|
13
13
|
from http import HTTPStatus
|
|
14
14
|
from importlib.util import find_spec
|
|
15
|
-
from typing import TYPE_CHECKING, Any, cast
|
|
15
|
+
from typing import TYPE_CHECKING, Any, NamedTuple, cast
|
|
16
16
|
from urllib.parse import urlsplit
|
|
17
17
|
|
|
18
|
+
from langchain_core.tools import StructuredTool
|
|
19
|
+
|
|
18
20
|
from managed_deepagents._agent_auth import AgentAuth
|
|
19
21
|
from managed_deepagents._agent_auth_http import (
|
|
20
22
|
AGENT_AUTH_TIMEOUT_SECONDS,
|
|
@@ -22,7 +24,10 @@ from managed_deepagents._agent_auth_http import (
|
|
|
22
24
|
request_agent_auth_json,
|
|
23
25
|
)
|
|
24
26
|
from managed_deepagents._connection_authorization import (
|
|
27
|
+
CONNECT_ON_USE_METADATA,
|
|
28
|
+
ConnectOnUse,
|
|
25
29
|
PendingCredential,
|
|
30
|
+
ToolCredentialRequiredError,
|
|
26
31
|
raise_credential_authorization_required,
|
|
27
32
|
resolve_user_connection_grants,
|
|
28
33
|
)
|
|
@@ -67,6 +72,8 @@ if TYPE_CHECKING or MCPAdapter is not None:
|
|
|
67
72
|
from fastmcp.client.transports import SSETransport, StreamableHttpTransport
|
|
68
73
|
from key_value.aio.stores.memory import MemoryStore
|
|
69
74
|
from mcp.client.caching import CacheConfig, CacheEntry, CacheKey
|
|
75
|
+
from mcp.types import Tool as McpTool
|
|
76
|
+
from pydantic import ValidationError
|
|
70
77
|
|
|
71
78
|
_AuthBase = httpx2.Auth
|
|
72
79
|
_CacheStoreBase = KeyValueResponseCacheStore
|
|
@@ -80,6 +87,13 @@ CACHE_TTL_MS = 5 * 60_000
|
|
|
80
87
|
CACHE_MAX_ENTRIES = 1024
|
|
81
88
|
|
|
82
89
|
|
|
90
|
+
class _DeferredCredential(NamedTuple):
|
|
91
|
+
"""A kit provider the caller connects on first use, with the tools LMT stored for it."""
|
|
92
|
+
|
|
93
|
+
credential: PendingCredential
|
|
94
|
+
tools: list[McpTool]
|
|
95
|
+
|
|
96
|
+
|
|
83
97
|
def load_managed_mcp_tools(connectors: McpServersDefinition) -> list[BaseTool]:
|
|
84
98
|
"""Build eager tools synchronously, reusing FastMCP's cached listings."""
|
|
85
99
|
return await_if_needed(load_eager_mcp_tools(connectors))
|
|
@@ -108,6 +122,11 @@ def mcp_credential_consumers(connectors: Sequence[object] | None) -> list[Creden
|
|
|
108
122
|
if langsmith
|
|
109
123
|
else None
|
|
110
124
|
),
|
|
125
|
+
connect_links=(
|
|
126
|
+
partial(managed_tools_connect_links, definition)
|
|
127
|
+
if langsmith and definition.config.get("jit_auth")
|
|
128
|
+
else None
|
|
129
|
+
),
|
|
111
130
|
)
|
|
112
131
|
)
|
|
113
132
|
return out
|
|
@@ -154,7 +173,7 @@ async def load_caller_mcp_tools(
|
|
|
154
173
|
for name, server in connectors.config["servers"].items()
|
|
155
174
|
if _uses_user_connection(server)
|
|
156
175
|
}
|
|
157
|
-
ready, pending = await asyncio.to_thread(
|
|
176
|
+
ready, pending, deferred = await asyncio.to_thread(
|
|
158
177
|
_resolve_langsmith_servers, connectors, _langsmith_server_names(connectors), context
|
|
159
178
|
)
|
|
160
179
|
if pending:
|
|
@@ -162,6 +181,9 @@ async def load_caller_mcp_tools(
|
|
|
162
181
|
servers.update(ready)
|
|
163
182
|
auth = {}
|
|
164
183
|
authorization: dict[str, object] = {}
|
|
184
|
+
stored: dict[str, list[_DeferredCredential]] = {}
|
|
185
|
+
jit_auth = connectors.config.get("jit_auth", False)
|
|
186
|
+
connect_on_use: set[str] = set()
|
|
165
187
|
caller_scope = [context.base_url, context.workspace_id, context.agent_id, context.principal_id]
|
|
166
188
|
for name, server in servers.items():
|
|
167
189
|
reference = server.get("connection")
|
|
@@ -178,14 +200,27 @@ async def load_caller_mcp_tools(
|
|
|
178
200
|
else:
|
|
179
201
|
headers = agent_auth_headers(api_key=context.api_key, workspace_id=context.workspace_id)
|
|
180
202
|
headers["x-langsmith-identity"] = context.principal_id
|
|
181
|
-
auth[name] = ManagedAuth(
|
|
182
|
-
|
|
203
|
+
auth[name] = ManagedAuth(
|
|
204
|
+
server["url"], headers=headers, managed_tools_server=name if jit_auth else None
|
|
205
|
+
)
|
|
206
|
+
if jit_auth:
|
|
207
|
+
connect_on_use.add(name)
|
|
208
|
+
scope: list[object] = [caller_scope, context.api_key]
|
|
209
|
+
if name in deferred:
|
|
210
|
+
# A new connection changes the live catalog; never serve the old one.
|
|
211
|
+
scope.append(sorted(entry.credential["slug"] for entry in deferred[name]))
|
|
212
|
+
stored[name] = deferred[name]
|
|
213
|
+
authorization[name] = scope
|
|
183
214
|
|
|
184
215
|
return await load_tools(
|
|
185
216
|
servers,
|
|
186
217
|
auth=auth,
|
|
187
218
|
authorization=authorization,
|
|
188
219
|
throw_on_load_error=connectors.config.get("throw_on_load_error", True),
|
|
220
|
+
stored=stored,
|
|
221
|
+
# Declaring elicitation makes LangSmith answer with a bare URL elicitation
|
|
222
|
+
# instead of the 428 that names the credential to connect.
|
|
223
|
+
without_elicitation=connect_on_use,
|
|
189
224
|
)
|
|
190
225
|
|
|
191
226
|
|
|
@@ -218,18 +253,24 @@ def _resolve_langsmith_servers(
|
|
|
218
253
|
connectors: McpServersDefinition,
|
|
219
254
|
server_names: Sequence[str],
|
|
220
255
|
context: AgentAuthContext,
|
|
221
|
-
) -> tuple[
|
|
222
|
-
|
|
256
|
+
) -> tuple[
|
|
257
|
+
dict[str, RemoteMcpServerConfig],
|
|
258
|
+
list[PendingCredential],
|
|
259
|
+
dict[str, list[_DeferredCredential]],
|
|
260
|
+
]:
|
|
261
|
+
"""Probe LangSmith MCP servers once: ready configs, pending and deferred credentials.
|
|
223
262
|
|
|
224
263
|
Shared by load (interrupt if pending) and the credential-gate collector
|
|
225
|
-
(return pending only).
|
|
226
|
-
|
|
264
|
+
(return pending only). With ``jit_auth``, a kit's missing credentials that
|
|
265
|
+
come with stored tools are deferred to first use instead of pending.
|
|
266
|
+
Transport failures follow ``throw_on_load_error``; authorization failures
|
|
267
|
+
are never skipped.
|
|
227
268
|
"""
|
|
228
269
|
if not server_names:
|
|
229
|
-
return {}, []
|
|
270
|
+
return {}, [], {}
|
|
230
271
|
matching = _matching_langsmith_servers(connectors, server_names, context.base_url.rstrip("/"))
|
|
231
272
|
if not matching:
|
|
232
|
-
return {}, []
|
|
273
|
+
return {}, [], {}
|
|
233
274
|
if not (context.api_key or "").strip():
|
|
234
275
|
raise RuntimeError("LangSmith MCP servers require LANGSMITH_API_KEY at runtime")
|
|
235
276
|
headers = agent_auth_headers(
|
|
@@ -237,11 +278,15 @@ def _resolve_langsmith_servers(
|
|
|
237
278
|
workspace_id=context.workspace_id,
|
|
238
279
|
)
|
|
239
280
|
headers["x-langsmith-identity"] = context.principal_id
|
|
281
|
+
jit_auth = connectors.config.get("jit_auth", False)
|
|
240
282
|
out: dict[str, RemoteMcpServerConfig] = {}
|
|
241
283
|
pending: list[PendingCredential] = []
|
|
284
|
+
deferred: dict[str, list[_DeferredCredential]] = {}
|
|
242
285
|
for server_name, declared, url in matching:
|
|
243
286
|
try:
|
|
244
|
-
required = _probe_langsmith_server_access(
|
|
287
|
+
required, on_use = _probe_langsmith_server_access(
|
|
288
|
+
server_name, url, headers, jit_auth=jit_auth
|
|
289
|
+
)
|
|
245
290
|
except OSError as exc:
|
|
246
291
|
if connectors.config.get("throw_on_load_error", True):
|
|
247
292
|
raise
|
|
@@ -255,7 +300,9 @@ def _resolve_langsmith_servers(
|
|
|
255
300
|
pending.extend(required)
|
|
256
301
|
continue
|
|
257
302
|
out[server_name] = _langsmith_server_config(declared)
|
|
258
|
-
|
|
303
|
+
if on_use:
|
|
304
|
+
deferred[server_name] = on_use
|
|
305
|
+
return out, pending, deferred
|
|
259
306
|
|
|
260
307
|
|
|
261
308
|
def collect_pending_managed_tools_credentials(
|
|
@@ -267,11 +314,38 @@ def collect_pending_managed_tools_credentials(
|
|
|
267
314
|
Incomplete 428s still raise a clear RuntimeError. Used by the
|
|
268
315
|
credential gate so Managed Tools misses combine with ordinary connection misses.
|
|
269
316
|
"""
|
|
270
|
-
|
|
317
|
+
_, pending, _ = _resolve_langsmith_servers(
|
|
271
318
|
connectors,
|
|
272
319
|
_langsmith_server_names(connectors),
|
|
273
320
|
context,
|
|
274
|
-
)
|
|
321
|
+
)
|
|
322
|
+
return pending
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def managed_tools_connect_links(
|
|
326
|
+
connectors: McpServersDefinition,
|
|
327
|
+
context: AgentAuthContext,
|
|
328
|
+
wanted: Mapping[str, Collection[str]],
|
|
329
|
+
) -> list[PendingCredential]:
|
|
330
|
+
"""Current connect links for the ``wanted`` slugs, listing only their kits."""
|
|
331
|
+
servers = [name for name in _langsmith_server_names(connectors) if wanted.get(name)]
|
|
332
|
+
matching = _matching_langsmith_servers(connectors, servers, context.base_url.rstrip("/"))
|
|
333
|
+
headers = agent_auth_headers(api_key=context.api_key, workspace_id=context.workspace_id)
|
|
334
|
+
headers["x-langsmith-identity"] = context.principal_id
|
|
335
|
+
links: list[PendingCredential] = []
|
|
336
|
+
for server_name, _declared, url in matching:
|
|
337
|
+
try:
|
|
338
|
+
pending, _ = _probe_langsmith_server_access(server_name, url, headers, jit_auth=False)
|
|
339
|
+
except (OSError, RuntimeError) as error:
|
|
340
|
+
# Each refused call still asks on its own with the link from its 428.
|
|
341
|
+
logger.warning(
|
|
342
|
+
'could not list connect links for LangSmith MCP server "%s": %s',
|
|
343
|
+
logger.log_identifier(server_name),
|
|
344
|
+
logger.safe_error_label(error),
|
|
345
|
+
)
|
|
346
|
+
continue
|
|
347
|
+
links.extend(c for c in pending if c["slug"] in wanted[server_name])
|
|
348
|
+
return links
|
|
275
349
|
|
|
276
350
|
|
|
277
351
|
def _langsmith_server_config(
|
|
@@ -287,10 +361,14 @@ def _probe_langsmith_server_access(
|
|
|
287
361
|
server_name: str,
|
|
288
362
|
url: str,
|
|
289
363
|
headers: Mapping[str, str],
|
|
290
|
-
|
|
364
|
+
*,
|
|
365
|
+
jit_auth: bool,
|
|
366
|
+
) -> tuple[list[PendingCredential], list[_DeferredCredential]]:
|
|
291
367
|
"""Return pending credentials from a complete 428 or a partial kit's ``_meta``.
|
|
292
368
|
|
|
293
|
-
|
|
369
|
+
With ``jit_auth``, ``_meta`` entries that carry stored tools are returned as
|
|
370
|
+
deferred instead of pending. An incomplete 428 raises. No pending
|
|
371
|
+
credentials means the server's connected tools load.
|
|
294
372
|
"""
|
|
295
373
|
status, payload = request_agent_auth_json(
|
|
296
374
|
"POST",
|
|
@@ -300,15 +378,15 @@ def _probe_langsmith_server_access(
|
|
|
300
378
|
timeout=AGENT_AUTH_TIMEOUT_SECONDS,
|
|
301
379
|
)
|
|
302
380
|
if status == HTTPStatus.OK:
|
|
303
|
-
return
|
|
381
|
+
return _credentials_from_langsmith_meta(payload, server_name, jit_auth=jit_auth)
|
|
304
382
|
if status != HTTPStatus.PRECONDITION_REQUIRED:
|
|
305
|
-
return []
|
|
383
|
+
return [], []
|
|
306
384
|
credentials = payload.get("credentials")
|
|
307
385
|
if isinstance(credentials, list):
|
|
308
|
-
return _pending_credentials_from_langsmith_gateway_428(credentials, server_name)
|
|
386
|
+
return _pending_credentials_from_langsmith_gateway_428(credentials, server_name), []
|
|
309
387
|
pending = _pending_credential_from_langsmith_428(payload, provider=server_name)
|
|
310
388
|
if pending is not None:
|
|
311
|
-
return [pending]
|
|
389
|
+
return [pending], []
|
|
312
390
|
verification_url = payload.get("verification_url")
|
|
313
391
|
if isinstance(verification_url, str) and verification_url:
|
|
314
392
|
raise RuntimeError(
|
|
@@ -321,14 +399,17 @@ def _probe_langsmith_server_access(
|
|
|
321
399
|
)
|
|
322
400
|
|
|
323
401
|
|
|
324
|
-
def
|
|
402
|
+
def _credentials_from_langsmith_meta(
|
|
325
403
|
payload: Mapping[str, object],
|
|
326
404
|
server_name: str,
|
|
327
|
-
|
|
405
|
+
*,
|
|
406
|
+
jit_auth: bool,
|
|
407
|
+
) -> tuple[list[PendingCredential], list[_DeferredCredential]]:
|
|
328
408
|
"""Map the missing credentials an ALLOW_PARTIAL tool kit lists in ``_meta``.
|
|
329
409
|
|
|
330
410
|
The kit's connected tools work without these, so entries without a
|
|
331
411
|
complete link are skipped with a warning instead of failing the run.
|
|
412
|
+
With ``jit_auth``, an entry's stored ``tools`` defer it to first use.
|
|
332
413
|
"""
|
|
333
414
|
result = payload.get("result")
|
|
334
415
|
meta = result.get("_meta") if isinstance(result, Mapping) else None
|
|
@@ -338,8 +419,9 @@ def _pending_credentials_from_langsmith_meta(
|
|
|
338
419
|
else None
|
|
339
420
|
)
|
|
340
421
|
if not isinstance(entries, list):
|
|
341
|
-
return []
|
|
422
|
+
return [], []
|
|
342
423
|
pending: list[PendingCredential] = []
|
|
424
|
+
deferred: list[_DeferredCredential] = []
|
|
343
425
|
for entry in entries:
|
|
344
426
|
credential = (
|
|
345
427
|
_pending_credential_from_langsmith_428(entry, provider=server_name)
|
|
@@ -349,8 +431,32 @@ def _pending_credentials_from_langsmith_meta(
|
|
|
349
431
|
if credential is None:
|
|
350
432
|
_warn_skipped_meta_credential(server_name, entry)
|
|
351
433
|
continue
|
|
434
|
+
tools = entry.get("tools") if jit_auth and isinstance(entry, Mapping) else None
|
|
435
|
+
stored = _stored_tool_definitions(server_name, tools) if isinstance(tools, list) else []
|
|
436
|
+
if stored:
|
|
437
|
+
deferred.append(_DeferredCredential(credential, stored))
|
|
438
|
+
continue
|
|
352
439
|
pending.append(credential)
|
|
353
|
-
return pending
|
|
440
|
+
return pending, deferred
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _stored_tool_definitions(server_name: str, tools: list[object]) -> list[McpTool]:
|
|
444
|
+
"""Validate the tool definitions LMT stores for an unconnected provider."""
|
|
445
|
+
require_runtime_dependency(MCPAdapter, "langchain[mcp]", "load MCP tools")
|
|
446
|
+
valid: list[McpTool] = []
|
|
447
|
+
for definition in tools:
|
|
448
|
+
try:
|
|
449
|
+
tool = McpTool.model_validate(definition)
|
|
450
|
+
except ValidationError:
|
|
451
|
+
continue
|
|
452
|
+
if tool.name and tool.input_schema.get("type") == "object":
|
|
453
|
+
valid.append(tool)
|
|
454
|
+
if len(valid) < len(tools):
|
|
455
|
+
logger.warning(
|
|
456
|
+
'skipped invalid stored tools for LangSmith MCP server "%s"',
|
|
457
|
+
logger.log_identifier(server_name),
|
|
458
|
+
)
|
|
459
|
+
return valid
|
|
354
460
|
|
|
355
461
|
|
|
356
462
|
def _warn_skipped_meta_credential(server_name: str, entry: object) -> None:
|
|
@@ -386,9 +492,24 @@ def _pending_credentials_from_langsmith_gateway_428(
|
|
|
386
492
|
Entries without a complete link cannot be completed from an interrupt, so
|
|
387
493
|
any of them raise with every missing name before an interrupt is shown.
|
|
388
494
|
"""
|
|
495
|
+
pending, unresolved = _partition_langsmith_428_entries(credentials, server_name)
|
|
496
|
+
if unresolved or not pending:
|
|
497
|
+
names = ", ".join(unresolved) if unresolved else server_name
|
|
498
|
+
raise RuntimeError(
|
|
499
|
+
f'LangSmith MCP server "{server_name}" requires credentials for {names}; '
|
|
500
|
+
"connect them in LangSmith Tools before running the agent"
|
|
501
|
+
)
|
|
502
|
+
return pending
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _partition_langsmith_428_entries(
|
|
506
|
+
entries: list[object],
|
|
507
|
+
server_name: str,
|
|
508
|
+
) -> tuple[list[PendingCredential], list[str]]:
|
|
509
|
+
"""Linked credentials, and labels for entries without a complete link."""
|
|
389
510
|
pending: list[PendingCredential] = []
|
|
390
511
|
unresolved: list[str] = []
|
|
391
|
-
for entry in
|
|
512
|
+
for entry in entries:
|
|
392
513
|
if not isinstance(entry, Mapping):
|
|
393
514
|
unresolved.append(server_name)
|
|
394
515
|
continue
|
|
@@ -398,13 +519,7 @@ def _pending_credentials_from_langsmith_gateway_428(
|
|
|
398
519
|
continue
|
|
399
520
|
label = entry.get("display_name") or entry.get("slug")
|
|
400
521
|
unresolved.append(label if isinstance(label, str) and label else server_name)
|
|
401
|
-
|
|
402
|
-
names = ", ".join(unresolved) if unresolved else server_name
|
|
403
|
-
raise RuntimeError(
|
|
404
|
-
f'LangSmith MCP server "{server_name}" requires credentials for {names}; '
|
|
405
|
-
"connect them in LangSmith Tools before running the agent"
|
|
406
|
-
)
|
|
407
|
-
return pending
|
|
522
|
+
return pending, unresolved
|
|
408
523
|
|
|
409
524
|
|
|
410
525
|
def _pending_credential_from_langsmith_428(
|
|
@@ -539,11 +654,14 @@ class ManagedAuth(_AuthBase):
|
|
|
539
654
|
token: Callable[[], Awaitable[str]] | None = None,
|
|
540
655
|
headers: Mapping[str, str] | None = None,
|
|
541
656
|
connection_slug: str | None = None,
|
|
657
|
+
managed_tools_server: str | None = None,
|
|
542
658
|
) -> None:
|
|
543
659
|
require_runtime_dependency(MCPAdapter, "langchain[mcp]", "load MCP tools")
|
|
544
660
|
self._origin = origin(url)
|
|
545
661
|
self._token = token
|
|
546
662
|
self._headers = dict(headers or {})
|
|
663
|
+
#: Set for a LangSmith tool kit whose calls may ask the caller to connect.
|
|
664
|
+
self._managed_tools_server = managed_tools_server
|
|
547
665
|
connection = f'MCP connection "{connection_slug}"' if connection_slug else "MCP connection"
|
|
548
666
|
self._rejected = f"{connection} was rejected by its server; reconnect it and retry"
|
|
549
667
|
|
|
@@ -561,6 +679,12 @@ class ManagedAuth(_AuthBase):
|
|
|
561
679
|
request.headers["Authorization"] = f"Bearer {token}"
|
|
562
680
|
request.headers.update(self._headers)
|
|
563
681
|
response = yield request
|
|
682
|
+
if (
|
|
683
|
+
response.status_code == HTTPStatus.PRECONDITION_REQUIRED
|
|
684
|
+
and self._managed_tools_server is not None
|
|
685
|
+
):
|
|
686
|
+
await response.aread()
|
|
687
|
+
raise _tool_credential_required(self._managed_tools_server, response)
|
|
564
688
|
if response.status_code != HTTPStatus.UNAUTHORIZED or self._token is None:
|
|
565
689
|
return
|
|
566
690
|
await response.aread()
|
|
@@ -577,6 +701,30 @@ class ManagedAuth(_AuthBase):
|
|
|
577
701
|
raise RuntimeError(self._rejected)
|
|
578
702
|
|
|
579
703
|
|
|
704
|
+
def _tool_credential_required(
|
|
705
|
+
server_name: str, response: httpx2.Response
|
|
706
|
+
) -> ToolCredentialRequiredError:
|
|
707
|
+
"""Map a kit's 428 for one tool call; credentials stay empty without a complete link."""
|
|
708
|
+
try:
|
|
709
|
+
body = response.json()
|
|
710
|
+
except ValueError:
|
|
711
|
+
body = None
|
|
712
|
+
entries = body.get("credentials") if isinstance(body, Mapping) else None
|
|
713
|
+
pending, unresolved = _partition_langsmith_428_entries(
|
|
714
|
+
entries if isinstance(entries, list) else [body], server_name
|
|
715
|
+
)
|
|
716
|
+
if unresolved or not pending:
|
|
717
|
+
logger.warning(
|
|
718
|
+
'could not read the connect link from a LangSmith MCP server "%s" refusal',
|
|
719
|
+
logger.log_identifier(server_name),
|
|
720
|
+
)
|
|
721
|
+
return ToolCredentialRequiredError(", ".join(dict.fromkeys(unresolved)) or server_name, [])
|
|
722
|
+
provider = ", ".join(
|
|
723
|
+
dict.fromkeys(credential.get("provider") or server_name for credential in pending)
|
|
724
|
+
)
|
|
725
|
+
return ToolCredentialRequiredError(provider, pending)
|
|
726
|
+
|
|
727
|
+
|
|
580
728
|
def _http_client_factory(
|
|
581
729
|
headers: dict[str, str] | None = None,
|
|
582
730
|
timeout: httpx2.Timeout | None = None,
|
|
@@ -636,15 +784,83 @@ async def _client(
|
|
|
636
784
|
|
|
637
785
|
|
|
638
786
|
async def _discover_tools(
|
|
639
|
-
name: str,
|
|
787
|
+
name: str,
|
|
788
|
+
client_factory: Callable[[], Awaitable[Client[Any]]],
|
|
789
|
+
stored: Sequence[_DeferredCredential] = (),
|
|
790
|
+
*,
|
|
791
|
+
elicitation: bool = True,
|
|
640
792
|
) -> list[BaseTool]:
|
|
641
793
|
# One-server native groups keep invocation independent of peers.
|
|
642
794
|
adapter_cls = cast(
|
|
643
795
|
"type[NativeMCPAdapter]",
|
|
644
796
|
require_runtime_dependency(MCPAdapter, "langchain[mcp]", "load MCP tools"),
|
|
645
797
|
)
|
|
646
|
-
|
|
647
|
-
|
|
798
|
+
group = ClientGroup({name: await client_factory()})
|
|
799
|
+
if elicitation:
|
|
800
|
+
# The adapter arms its clients to answer elicitation with interrupts.
|
|
801
|
+
armed = adapter_cls(group).client
|
|
802
|
+
if isinstance(armed, ClientGroup):
|
|
803
|
+
group = armed
|
|
804
|
+
# Loaded with MCPAdapter above, which this path already required.
|
|
805
|
+
from langchain.mcp import as_langchain_tool as convert # noqa: PLC0415
|
|
806
|
+
|
|
807
|
+
async with group:
|
|
808
|
+
member = group.clients[name]
|
|
809
|
+
tools: list[BaseTool] = []
|
|
810
|
+
for tool in await group.list_tools(cache_mode="use"):
|
|
811
|
+
native = await convert(tool, group)
|
|
812
|
+
if not elicitation:
|
|
813
|
+
upstream = tool.model_copy(update={"name": tool.name.removeprefix(f"{name}_")})
|
|
814
|
+
native = native.model_copy(update={"coroutine": _on_own_session(upstream, member)})
|
|
815
|
+
tools.append(native)
|
|
816
|
+
if stored:
|
|
817
|
+
tools += await _stored_tools(name, stored, member, {tool.name for tool in tools})
|
|
818
|
+
return tools
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
async def _stored_tools(
|
|
822
|
+
name: str,
|
|
823
|
+
deferred: Sequence[_DeferredCredential],
|
|
824
|
+
client: Client[Any],
|
|
825
|
+
listed: set[str],
|
|
826
|
+
) -> list[BaseTool]:
|
|
827
|
+
"""Bind stored definitions under native names; calls go to the server by raw name.
|
|
828
|
+
|
|
829
|
+
Each carries the credential it needs, so the gate can ask once per model step.
|
|
830
|
+
"""
|
|
831
|
+
# Loaded with MCPAdapter above, which this path already required.
|
|
832
|
+
from langchain.mcp import as_langchain_tool as convert # noqa: PLC0415
|
|
833
|
+
|
|
834
|
+
tools: list[BaseTool] = []
|
|
835
|
+
for credential, definitions in deferred:
|
|
836
|
+
connect: ConnectOnUse = {"server": name, "credential": credential}
|
|
837
|
+
for tool in definitions:
|
|
838
|
+
qualified = f"{name}_{tool.name}"
|
|
839
|
+
if qualified in listed:
|
|
840
|
+
continue
|
|
841
|
+
listed.add(qualified)
|
|
842
|
+
native = await convert(tool, client)
|
|
843
|
+
metadata = {**(native.metadata or {}), CONNECT_ON_USE_METADATA: connect}
|
|
844
|
+
coroutine = _on_own_session(tool, client)
|
|
845
|
+
tools.append(
|
|
846
|
+
native.model_copy(
|
|
847
|
+
update={"name": qualified, "metadata": metadata, "coroutine": coroutine}
|
|
848
|
+
)
|
|
849
|
+
)
|
|
850
|
+
return tools
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _on_own_session(tool: McpTool, client: Client[Any]) -> Callable[..., Awaitable[object]]:
|
|
854
|
+
"""Call ``tool`` on its own session; a kit's 428 ends the session, and any calls sharing it."""
|
|
855
|
+
from langchain.mcp import as_langchain_tool as convert # noqa: PLC0415
|
|
856
|
+
|
|
857
|
+
async def call(**arguments: object) -> object:
|
|
858
|
+
isolated = await convert(tool, client.new())
|
|
859
|
+
if not isinstance(isolated, StructuredTool) or isolated.coroutine is None:
|
|
860
|
+
raise TypeError("langchain.mcp returned a tool without a coroutine")
|
|
861
|
+
return await isolated.coroutine(**arguments)
|
|
862
|
+
|
|
863
|
+
return call
|
|
648
864
|
|
|
649
865
|
|
|
650
866
|
async def load_tools(
|
|
@@ -653,8 +869,15 @@ async def load_tools(
|
|
|
653
869
|
auth: Mapping[str, httpx2.Auth],
|
|
654
870
|
authorization: Mapping[str, object],
|
|
655
871
|
throw_on_load_error: bool = True,
|
|
872
|
+
stored: Mapping[str, Sequence[_DeferredCredential]] | None = None,
|
|
873
|
+
without_elicitation: Collection[str] = (),
|
|
656
874
|
) -> list[BaseTool]:
|
|
657
|
-
"""Discover detached native tools using one stable, authorization-scoped cache.
|
|
875
|
+
"""Discover detached native tools using one stable, authorization-scoped cache.
|
|
876
|
+
|
|
877
|
+
``stored`` adds a server's tool definitions that its listing leaves out
|
|
878
|
+
(LangSmith tool kits' unconnected providers) through the same native path.
|
|
879
|
+
Servers in ``without_elicitation`` connect without declaring elicitation.
|
|
880
|
+
"""
|
|
658
881
|
require_runtime_dependency(MCPAdapter, "langchain[mcp]", "load MCP tools")
|
|
659
882
|
tools: list[BaseTool] = []
|
|
660
883
|
names: set[str] = set()
|
|
@@ -664,7 +887,12 @@ async def load_tools(
|
|
|
664
887
|
)
|
|
665
888
|
try:
|
|
666
889
|
with build_step(name):
|
|
667
|
-
server_tools = await _discover_tools(
|
|
890
|
+
server_tools = await _discover_tools(
|
|
891
|
+
name,
|
|
892
|
+
client_factory,
|
|
893
|
+
(stored or {}).get(name, ()),
|
|
894
|
+
elicitation=name not in without_elicitation,
|
|
895
|
+
)
|
|
668
896
|
except Exception as error:
|
|
669
897
|
if throw_on_load_error:
|
|
670
898
|
raise
|
|
@@ -7,6 +7,13 @@ LangGraph interrupt; OAuth slugs include connect URLs, opaque slugs request
|
|
|
7
7
|
password-style input. The tools a grant unlocks are loaded on first use and
|
|
8
8
|
cached per caller when the consumer opts in. MCP uses its native listing cache.
|
|
9
9
|
Required integrations without a caller end with sign-in guidance.
|
|
10
|
+
|
|
11
|
+
A tool call refused until its credentials are connected (LangSmith tool kits
|
|
12
|
+
with ``jit_auth``) interrupts the caller and retries that call once on resume.
|
|
13
|
+
Without a caller to ask (no caller, or a scheduled run), or still unconnected
|
|
14
|
+
after the resume, the call returns a tool error and the run continues.
|
|
15
|
+
Calls to tools that declare the credential they need ask once per model
|
|
16
|
+
step, before any of them runs.
|
|
10
17
|
"""
|
|
11
18
|
|
|
12
19
|
from __future__ import annotations
|
|
@@ -16,22 +23,24 @@ import contextvars
|
|
|
16
23
|
import threading
|
|
17
24
|
import time
|
|
18
25
|
import warnings
|
|
19
|
-
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
26
|
+
from collections.abc import Awaitable, Callable, Collection, Mapping, Sequence
|
|
20
27
|
from concurrent.futures import Future, ThreadPoolExecutor
|
|
21
28
|
from dataclasses import dataclass, field
|
|
22
|
-
from typing import TYPE_CHECKING, Any, Literal, TypedDict
|
|
29
|
+
from typing import TYPE_CHECKING, Annotated, Any, Literal, NotRequired, TypedDict
|
|
23
30
|
|
|
24
31
|
from langchain.agents.middleware.types import (
|
|
25
32
|
AgentMiddleware,
|
|
26
33
|
AgentState,
|
|
34
|
+
ExtendedModelResponse,
|
|
27
35
|
JumpTo,
|
|
28
36
|
ModelCallResult,
|
|
29
37
|
ModelRequest,
|
|
30
38
|
ModelResponse,
|
|
39
|
+
PrivateStateAttr,
|
|
31
40
|
ToolCallRequest,
|
|
32
41
|
hook_config,
|
|
33
42
|
)
|
|
34
|
-
from langchain_core.messages import ToolMessage
|
|
43
|
+
from langchain_core.messages import AIMessage, ToolMessage
|
|
35
44
|
from langchain_core.tools import BaseTool
|
|
36
45
|
from langgraph.runtime import Runtime
|
|
37
46
|
from langgraph.types import Command, interrupt
|
|
@@ -42,10 +51,14 @@ from managed_deepagents._agent_auth import (
|
|
|
42
51
|
)
|
|
43
52
|
from managed_deepagents._agent_auth_http import CredentialStoreUnavailableError
|
|
44
53
|
from managed_deepagents._connection_authorization import (
|
|
54
|
+
CONNECT_ON_USE_METADATA,
|
|
55
|
+
ConnectOnUse,
|
|
45
56
|
CredentialAuthorizationDeferredError,
|
|
46
57
|
CredentialAuthorizationRequiredInterrupt,
|
|
47
58
|
PendingCredential,
|
|
59
|
+
ToolCredentialRequiredError,
|
|
48
60
|
collect_pending_user_connection_credentials,
|
|
61
|
+
credential_authorization_interrupt,
|
|
49
62
|
defer_credential_interrupts,
|
|
50
63
|
raise_credential_authorization_required,
|
|
51
64
|
resolve_user_connection_grants,
|
|
@@ -62,7 +75,9 @@ from managed_deepagents._identity_runtime import (
|
|
|
62
75
|
build_runtime_identity,
|
|
63
76
|
resolve_runtime_configurable,
|
|
64
77
|
)
|
|
78
|
+
from managed_deepagents._log import logger
|
|
65
79
|
from managed_deepagents._managed_tools import with_managed_runtime
|
|
80
|
+
from managed_deepagents._run_input import is_scheduled_execution
|
|
66
81
|
from managed_deepagents._telemetry.otel.context import LogAttributes, record_log
|
|
67
82
|
|
|
68
83
|
if TYPE_CHECKING:
|
|
@@ -98,6 +113,26 @@ class CredentialConsumer:
|
|
|
98
113
|
#: Optional collector for extra pending credentials (no interrupt).
|
|
99
114
|
#: MCP uses this for LangSmith Managed Tools OAuth probes.
|
|
100
115
|
collect_pending_credentials: Callable[[AgentAuthContext], list[PendingCredential]] | None = None
|
|
116
|
+
#: Lists connect links for the slugs of each server whose tools ask on use.
|
|
117
|
+
connect_links: (
|
|
118
|
+
Callable[[AgentAuthContext, Mapping[str, Collection[str]]], list[PendingCredential]] | None
|
|
119
|
+
) = None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _ConnectState(AgentState[Any]):
|
|
123
|
+
"""The connect prompt one model step's calls need, asked once after the step."""
|
|
124
|
+
|
|
125
|
+
#: Links for the credentials the last model step's calls need, asked once after it.
|
|
126
|
+
mda_connect_request: NotRequired[Annotated[list[PendingCredential] | None, PrivateStateAttr]]
|
|
127
|
+
#: Slugs asked about this step; their refused calls do not ask again.
|
|
128
|
+
mda_connect_asked: NotRequired[Annotated[list[str], PrivateStateAttr]]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class _ConnectUpdate(TypedDict, total=False):
|
|
132
|
+
"""A state update to ``_ConnectState``'s keys."""
|
|
133
|
+
|
|
134
|
+
mda_connect_request: list[PendingCredential] | None
|
|
135
|
+
mda_connect_asked: list[str]
|
|
101
136
|
|
|
102
137
|
|
|
103
138
|
@dataclass
|
|
@@ -114,7 +149,7 @@ _tool_load_locks: dict[tuple[int, str], threading.Lock] = {}
|
|
|
114
149
|
|
|
115
150
|
def create_credential_gate_middleware(
|
|
116
151
|
consumers: Sequence[CredentialConsumer],
|
|
117
|
-
) -> AgentMiddleware | None:
|
|
152
|
+
) -> AgentMiddleware[Any, Any, Any] | None:
|
|
118
153
|
"""Install the gate when a declaration names a user-owned connection."""
|
|
119
154
|
if not consumers:
|
|
120
155
|
return None
|
|
@@ -122,9 +157,11 @@ def create_credential_gate_middleware(
|
|
|
122
157
|
return _CredentialGateMiddleware(consumers)
|
|
123
158
|
|
|
124
159
|
|
|
125
|
-
class _CredentialGateMiddleware(AgentMiddleware[
|
|
160
|
+
class _CredentialGateMiddleware(AgentMiddleware[_ConnectState, Any, Any]):
|
|
126
161
|
"""Reuse loaded tools within one verified run without checkpointing credentials."""
|
|
127
162
|
|
|
163
|
+
state_schema = _ConnectState
|
|
164
|
+
|
|
128
165
|
def __init__(self, consumers: Sequence[CredentialConsumer]) -> None:
|
|
129
166
|
self._consumers = consumers
|
|
130
167
|
self._lock = threading.Lock()
|
|
@@ -178,7 +215,9 @@ class _CredentialGateMiddleware(AgentMiddleware[AgentState[Any], Any, Any]):
|
|
|
178
215
|
request: ModelRequest[Any],
|
|
179
216
|
handler: Callable[[ModelRequest[Any]], ModelResponse[Any]],
|
|
180
217
|
) -> ModelCallResult[Any]:
|
|
181
|
-
|
|
218
|
+
tools = _model_tools_for(self._tools, request)
|
|
219
|
+
response = handler(_with_extra_tools(request, tools))
|
|
220
|
+
return _with_connect_request(self._consumers, request, tools, response)
|
|
182
221
|
|
|
183
222
|
async def awrap_model_call(
|
|
184
223
|
self,
|
|
@@ -186,7 +225,20 @@ class _CredentialGateMiddleware(AgentMiddleware[AgentState[Any], Any, Any]):
|
|
|
186
225
|
handler: Callable[[ModelRequest[Any]], Awaitable[ModelResponse[Any]]],
|
|
187
226
|
) -> ModelCallResult[Any]:
|
|
188
227
|
tools = await asyncio.to_thread(_model_tools_for, self._tools, request)
|
|
189
|
-
|
|
228
|
+
response = await handler(_with_extra_tools(request, tools))
|
|
229
|
+
return await asyncio.to_thread(
|
|
230
|
+
_with_connect_request, self._consumers, request, tools, response
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
def after_model(self, state: _ConnectState, runtime: Runtime[Any]) -> dict[str, Any] | None:
|
|
234
|
+
del runtime
|
|
235
|
+
update = _ask_once(state)
|
|
236
|
+
return dict(update) if update is not None else None
|
|
237
|
+
|
|
238
|
+
async def aafter_model(
|
|
239
|
+
self, state: _ConnectState, runtime: Runtime[Any]
|
|
240
|
+
) -> dict[str, Any] | None:
|
|
241
|
+
return self.after_model(state, runtime)
|
|
190
242
|
|
|
191
243
|
def wrap_tool_call(
|
|
192
244
|
self,
|
|
@@ -219,7 +271,7 @@ def _wrap_tool_call(
|
|
|
219
271
|
except CredentialStoreUnavailableError as error:
|
|
220
272
|
_record_credential_unavailable(error, "tool_call")
|
|
221
273
|
return _credential_error_message(request)
|
|
222
|
-
return
|
|
274
|
+
return _call_connecting(_with_dynamic_tool(request, tools), handler)
|
|
223
275
|
|
|
224
276
|
|
|
225
277
|
async def _awrap_tool_call(
|
|
@@ -234,7 +286,7 @@ async def _awrap_tool_call(
|
|
|
234
286
|
except CredentialStoreUnavailableError as error:
|
|
235
287
|
_record_credential_unavailable(error, "tool_call")
|
|
236
288
|
return _credential_error_message(request)
|
|
237
|
-
return await
|
|
289
|
+
return await _acall_connecting(_with_dynamic_tool(request, tools), handler)
|
|
238
290
|
|
|
239
291
|
|
|
240
292
|
def _record_credential_unavailable(
|
|
@@ -467,6 +519,174 @@ def _with_dynamic_tool(request: ToolCallRequest, tools: Sequence[BaseTool]) -> T
|
|
|
467
519
|
return request.override(tool=match)
|
|
468
520
|
|
|
469
521
|
|
|
522
|
+
def _call_connecting(
|
|
523
|
+
request: ToolCallRequest,
|
|
524
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
|
|
525
|
+
) -> ToolMessage | Command[Any]:
|
|
526
|
+
try:
|
|
527
|
+
return handler(request)
|
|
528
|
+
except Exception as error:
|
|
529
|
+
missing = _credential_refusal(error)
|
|
530
|
+
if missing is None:
|
|
531
|
+
raise
|
|
532
|
+
if not _ask_to_connect(request, missing):
|
|
533
|
+
return _not_connected(request, missing)
|
|
534
|
+
# A resume value is never evidence of a connection; only the retry decides.
|
|
535
|
+
try:
|
|
536
|
+
return handler(request)
|
|
537
|
+
except Exception as error:
|
|
538
|
+
refusal = _credential_refusal(error)
|
|
539
|
+
if refusal is None:
|
|
540
|
+
raise
|
|
541
|
+
return _not_connected(request, refusal)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
async def _acall_connecting(
|
|
545
|
+
request: ToolCallRequest,
|
|
546
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
|
|
547
|
+
) -> ToolMessage | Command[Any]:
|
|
548
|
+
try:
|
|
549
|
+
return await handler(request)
|
|
550
|
+
except Exception as error:
|
|
551
|
+
missing = _credential_refusal(error)
|
|
552
|
+
if missing is None:
|
|
553
|
+
raise
|
|
554
|
+
if not _ask_to_connect(request, missing):
|
|
555
|
+
return _not_connected(request, missing)
|
|
556
|
+
try:
|
|
557
|
+
return await handler(request)
|
|
558
|
+
except Exception as error:
|
|
559
|
+
refusal = _credential_refusal(error)
|
|
560
|
+
if refusal is None:
|
|
561
|
+
raise
|
|
562
|
+
return _not_connected(request, refusal)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _credential_refusal(error: BaseException) -> ToolCredentialRequiredError | None:
|
|
566
|
+
"""The refusal behind ``error``, through any middleware that wrapped it."""
|
|
567
|
+
cause: BaseException | None = error
|
|
568
|
+
while cause is not None:
|
|
569
|
+
if isinstance(cause, ToolCredentialRequiredError):
|
|
570
|
+
return cause
|
|
571
|
+
cause = cause.__cause__
|
|
572
|
+
return None
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _with_connect_request(
|
|
576
|
+
consumers: Sequence[CredentialConsumer],
|
|
577
|
+
request: ModelRequest[Any],
|
|
578
|
+
tools: Sequence[BaseTool],
|
|
579
|
+
response: ModelResponse[Any],
|
|
580
|
+
) -> ModelCallResult[Any]:
|
|
581
|
+
"""List fresh links for the credentials this step's calls need, for ``after_model``.
|
|
582
|
+
|
|
583
|
+
Tools load once per run, so links are listed here rather than read from the
|
|
584
|
+
tools. Listing in the model step keeps a resumed run, which replays
|
|
585
|
+
``after_model`` but not the model call, from starting new connect sessions.
|
|
586
|
+
"""
|
|
587
|
+
update: _ConnectUpdate = {}
|
|
588
|
+
needed = _connect_on_use(tools, response)
|
|
589
|
+
caller = _connecting_caller(request.runtime) if needed else None
|
|
590
|
+
links = _connect_links(consumers, caller.context, needed) if caller is not None else []
|
|
591
|
+
if links:
|
|
592
|
+
update["mda_connect_request"] = links
|
|
593
|
+
elif request.state.get("mda_connect_request"):
|
|
594
|
+
# An unanswered prompt from an earlier turn must not be asked again.
|
|
595
|
+
update["mda_connect_request"] = None
|
|
596
|
+
if request.state.get("mda_connect_asked"):
|
|
597
|
+
update["mda_connect_asked"] = []
|
|
598
|
+
if not update:
|
|
599
|
+
return response
|
|
600
|
+
return ExtendedModelResponse(model_response=response, command=Command(update=update))
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _connect_on_use(
|
|
604
|
+
tools: Sequence[BaseTool], response: ModelResponse[Any]
|
|
605
|
+
) -> dict[str, ConnectOnUse]:
|
|
606
|
+
"""The credentials stored tools need for the calls in ``response``, by slug."""
|
|
607
|
+
connectable: dict[str, ConnectOnUse] = {
|
|
608
|
+
tool.name: tool.metadata[CONNECT_ON_USE_METADATA]
|
|
609
|
+
for tool in tools
|
|
610
|
+
if tool.metadata and CONNECT_ON_USE_METADATA in tool.metadata
|
|
611
|
+
}
|
|
612
|
+
needed: dict[str, ConnectOnUse] = {}
|
|
613
|
+
if not connectable:
|
|
614
|
+
return needed
|
|
615
|
+
for message in response.result:
|
|
616
|
+
if not isinstance(message, AIMessage):
|
|
617
|
+
continue
|
|
618
|
+
for call in message.tool_calls:
|
|
619
|
+
connect = connectable.get(call["name"])
|
|
620
|
+
if connect is not None:
|
|
621
|
+
needed.setdefault(connect["credential"]["slug"], connect)
|
|
622
|
+
return needed
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _connect_links(
|
|
626
|
+
consumers: Sequence[CredentialConsumer],
|
|
627
|
+
context: AgentAuthContext,
|
|
628
|
+
needed: Mapping[str, ConnectOnUse],
|
|
629
|
+
) -> list[PendingCredential]:
|
|
630
|
+
"""Fresh links for the needed slugs; a provider connected since load is not listed."""
|
|
631
|
+
wanted: dict[str, set[str]] = {}
|
|
632
|
+
for slug, connect in needed.items():
|
|
633
|
+
wanted.setdefault(connect["server"], set()).add(slug)
|
|
634
|
+
linked: list[PendingCredential] = []
|
|
635
|
+
for consumer in consumers:
|
|
636
|
+
if consumer.connect_links is None:
|
|
637
|
+
continue
|
|
638
|
+
try:
|
|
639
|
+
linked.extend(consumer.connect_links(context, wanted))
|
|
640
|
+
except Exception as error: # noqa: BLE001 - each refused call still asks with its 428's link
|
|
641
|
+
logger.warning("could not list connect links: %s", logger.safe_error_label(error))
|
|
642
|
+
by_slug = {credential["slug"]: credential for credential in reversed(linked)}
|
|
643
|
+
return [by_slug[slug] for slug in needed if slug in by_slug]
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def _ask_once(state: _ConnectState) -> _ConnectUpdate | None:
|
|
647
|
+
credentials = state.get("mda_connect_request")
|
|
648
|
+
if not credentials:
|
|
649
|
+
return None
|
|
650
|
+
_interrupt(credential_authorization_interrupt(credentials))
|
|
651
|
+
return {
|
|
652
|
+
"mda_connect_request": None,
|
|
653
|
+
"mda_connect_asked": [credential["slug"] for credential in credentials],
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _ask_to_connect(request: ToolCallRequest, missing: ToolCredentialRequiredError) -> bool:
|
|
658
|
+
"""Interrupt with the connect links when this run's caller can follow them.
|
|
659
|
+
|
|
660
|
+
A credential already asked about this step returns its tool error instead.
|
|
661
|
+
"""
|
|
662
|
+
asked = request.state.get("mda_connect_asked") or ()
|
|
663
|
+
if (
|
|
664
|
+
not missing.credentials
|
|
665
|
+
or all(credential["slug"] in asked for credential in missing.credentials)
|
|
666
|
+
or _connecting_caller(request.runtime) is None
|
|
667
|
+
):
|
|
668
|
+
return False
|
|
669
|
+
_interrupt(credential_authorization_interrupt(missing.credentials))
|
|
670
|
+
return True
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _connecting_caller(runtime: object | None) -> _Caller | None:
|
|
674
|
+
"""The caller the pre-run gate would ask; a schedule has no one to answer."""
|
|
675
|
+
caller = _auth_context(runtime)
|
|
676
|
+
if caller is None or is_scheduled_execution(resolve_runtime_configurable(runtime)):
|
|
677
|
+
return None
|
|
678
|
+
return caller
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _not_connected(request: ToolCallRequest, missing: ToolCredentialRequiredError) -> ToolMessage:
|
|
682
|
+
return ToolMessage(
|
|
683
|
+
content=f"{missing.provider} is not connected. Connect it in LangSmith, then try again.",
|
|
684
|
+
tool_call_id=request.tool_call["id"],
|
|
685
|
+
name=request.tool_call["name"],
|
|
686
|
+
status="error",
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
|
|
470
690
|
def _interrupt(payload: CredentialAuthorizationRequiredInterrupt) -> None:
|
|
471
691
|
interrupt(payload)
|
|
472
692
|
|
{managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: managed-deepagents
|
|
3
|
-
Version: 0.10.2.
|
|
3
|
+
Version: 0.10.2.dev8
|
|
4
4
|
Summary: Managed Deep Agents — the define_deep_agent authoring interface plus the CLI that compiles and deploys a code-first Deep Agent repository to a managed LangGraph runtime.
|
|
5
5
|
Author: LangChain
|
|
6
6
|
License: MIT
|
|
@@ -1816,6 +1816,15 @@ reports its connection URL; complete OAuth there, then retry the run. API-key
|
|
|
1816
1816
|
MCP servers require the caller to connect the key in LangSmith Tools before
|
|
1817
1817
|
invoking one of their tools.
|
|
1818
1818
|
|
|
1819
|
+
A LangSmith tool kit asks for every unconnected provider before the run starts.
|
|
1820
|
+
Pass `jit_auth=True` to `define_mcp` to ask on use instead: the kit's tools for
|
|
1821
|
+
unconnected providers are still offered to the model. When the model calls
|
|
1822
|
+
them, the run interrupts once per model step with the connect links for the
|
|
1823
|
+
providers those calls need, then runs the calls after it resumes. If the run
|
|
1824
|
+
resumes without a connection, or nobody can connect in this run (no signed-in
|
|
1825
|
+
caller, or a scheduled run), those calls return a tool error and the run
|
|
1826
|
+
continues.
|
|
1827
|
+
|
|
1819
1828
|
Deploy the project first, then provision its connections with
|
|
1820
1829
|
`mda connections create`. Agent-owned opaque secrets are scoped to that
|
|
1821
1830
|
deployment, so the command refuses to create one before `mda deploy`.
|
{managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/RECORD
RENAMED
|
@@ -7,11 +7,11 @@ managed_deepagents/_browser_recording.py,sha256=jkcxJfXVyaKUpjp6B9fR3qguMWHPevpQ
|
|
|
7
7
|
managed_deepagents/_channel.py,sha256=EabaswVclNB129GyIQiTSCbbKM4_2H3J_mC2XyKpn-o,5853
|
|
8
8
|
managed_deepagents/_channel_icon.py,sha256=ECHCv1DWKpFKKTHzppSMVFq7gcdoK4udko04J-iWMVg,3691
|
|
9
9
|
managed_deepagents/_cli.py,sha256=jVaw2i1ysdRoWziMdPFmRXtKry_baYGRspyzyIeGWoU,1688
|
|
10
|
-
managed_deepagents/_connection_authorization.py,sha256=
|
|
10
|
+
managed_deepagents/_connection_authorization.py,sha256=AnX7CRtP59RWsNmzzt7BoVqX8vjervcndUVuu0ZJk28,6598
|
|
11
11
|
managed_deepagents/_connections.py,sha256=BW4vTkPxJDasss-WoRJawcM-kU7OeYSzchHL4ovek70,25829
|
|
12
12
|
managed_deepagents/_connector.py,sha256=s9FTVzs130NOhHYokBgQa6VWy47srUKp2lC56XoY9as,8620
|
|
13
13
|
managed_deepagents/_cors.py,sha256=WAlD_PgLFVAN1BAQaYU44DKctAJk4xQnFZ0I-9EwMng,7814
|
|
14
|
-
managed_deepagents/_credential_gate.py,sha256=
|
|
14
|
+
managed_deepagents/_credential_gate.py,sha256=W0sNSCQwzrB1GUIRv3djdT5lZ_GWyGQZrNcz18wxzi4,27348
|
|
15
15
|
managed_deepagents/_eval_filesystem.py,sha256=_oRR0CUzpO7XND2JkkNUZH63m5kwxmGcR7cfqfFO378,8768
|
|
16
16
|
managed_deepagents/_extension.py,sha256=MqCWS4AGxiURPtLlA2y_tWKdRL8Zu1-VZyQ6Q3HDgzc,5315
|
|
17
17
|
managed_deepagents/_graph_build_timing.py,sha256=4tH2PkHnTks-ewUqbzyJ7bQ0cE-ZsfwtOzVspezTnMs,4559
|
|
@@ -50,7 +50,7 @@ managed_deepagents/run_context.py,sha256=IayZdcpPrKVss70Hro8qI-EWtL94HZt4JKefzec
|
|
|
50
50
|
managed_deepagents/runtime.py,sha256=ID3jCEgtxtVyZ8ePKbc4FW4hwh3mwEtndCFl_o60tUY,114229
|
|
51
51
|
managed_deepagents/sandbox.py,sha256=OAZ9BsvuJIIgvE51YR2tL7rwFcjE4q1RaR2dVfNkBzY,5647
|
|
52
52
|
managed_deepagents/schedules.py,sha256=XROsDs-QwCWH0yEwakIN5Rhl5aM06eZX5-JFJ-KG1To,5898
|
|
53
|
-
managed_deepagents/_binaries/mda.exe,sha256=
|
|
53
|
+
managed_deepagents/_binaries/mda.exe,sha256=Ld4uZrwj7iIiRIXU6j97PJ6LFV7Cg__xuth6V8olxWE,5123072
|
|
54
54
|
managed_deepagents/_channels/__init__.py,sha256=mMgqza7EWRjhJM0lXlFd-W6wBYZrFkpLQ4_30Bpij7k,249
|
|
55
55
|
managed_deepagents/_channels/actor.py,sha256=3d_1-ia6vwVjXkw7PYn5gg6BjnlPwRXW4nW2C5vAO7c,5203
|
|
56
56
|
managed_deepagents/_channels/assistant_text.py,sha256=nf00-KJXNev-e_TkAK_8SBI3J9TiOis1GkGV_zT5048,8472
|
|
@@ -115,9 +115,9 @@ managed_deepagents/_concurrency/batch_processor.py,sha256=2aCVMckCCTs8-4vndRWJo9
|
|
|
115
115
|
managed_deepagents/_concurrency/deadline.py,sha256=DEZpiUJZaXru10A2DwkUoBvCEkusLAThBYrK-5ZWlec,1159
|
|
116
116
|
managed_deepagents/_connectors/__init__.py,sha256=Ei-DvDmA-F2Bord6WuM7UtWtnuVt3u7CRSPKFqpHFhA,537
|
|
117
117
|
managed_deepagents/_connectors/tool_selection.py,sha256=-dtrHi8o4FsXG70V4CWgzL2UVG-89P3TU1Xk8UEdyDU,3029
|
|
118
|
-
managed_deepagents/_connectors/mcp/__init__.py,sha256=
|
|
118
|
+
managed_deepagents/_connectors/mcp/__init__.py,sha256=o847QDD82-5CV3Fg6kB0wLde82cRfDG_wXcy4LDXUjw,18138
|
|
119
119
|
managed_deepagents/_connectors/mcp/langsmith_url.py,sha256=RbqcvQPOyTOUOca6zRsROapeGrKUNyQ8dSje5FWMwas,1683
|
|
120
|
-
managed_deepagents/_connectors/mcp/load.py,sha256=
|
|
120
|
+
managed_deepagents/_connectors/mcp/load.py,sha256=2qMCXUhZhtdc0es9GnBZ5kVOcRIkXo2aK8jDJnuQ0oE,35178
|
|
121
121
|
managed_deepagents/_memory/__init__.py,sha256=Z6GljzgF3XojNPGH1RN93TZhgCVhcxvS5IaotZ91dOk,371
|
|
122
122
|
managed_deepagents/_memory/async_util.py,sha256=gyN1PqRp94zSC12CZjD_daihtuf4rYTws_G7OIeW86k,1783
|
|
123
123
|
managed_deepagents/_memory/context_io.py,sha256=twvf8xPBP77uipZel9EyUUxQDggD9aI_eYc34QC0SRE,1666
|
|
@@ -151,9 +151,9 @@ managed_deepagents/identity/__init__.py,sha256=uZUKDHtfBc0n-T2xoJEFMqMplmXwAK7hb
|
|
|
151
151
|
managed_deepagents/identity/claims.py,sha256=prby7r_8Lww3MmoBm8PX6PsSGE3GwSHkr8mVIz_08nU,1180
|
|
152
152
|
managed_deepagents/identity/options.py,sha256=x_yMbXEFR7zXyehEjDHG2qjAlukXjrRBcQLcM6IndLM,2550
|
|
153
153
|
managed_deepagents/identity/supabase.py,sha256=8uobl3WCrQL_ieSXG8KTLf1th7Qjim9liZT50HeaJE0,6026
|
|
154
|
-
managed_deepagents-0.10.2.
|
|
155
|
-
managed_deepagents-0.10.2.
|
|
156
|
-
managed_deepagents-0.10.2.
|
|
157
|
-
managed_deepagents-0.10.2.
|
|
158
|
-
managed_deepagents-0.10.2.
|
|
159
|
-
managed_deepagents-0.10.2.
|
|
154
|
+
managed_deepagents-0.10.2.dev8.dist-info/licenses/LICENSE,sha256=WnPZQQ608ojZUkXl7BW6VbKloIAibZiGm1K6cjeZOL8,1066
|
|
155
|
+
managed_deepagents-0.10.2.dev8.dist-info/METADATA,sha256=4Ga-5yVhp-ASxiN6Qg8T-dW8BNT3aoS1at0NskSiwR0,93570
|
|
156
|
+
managed_deepagents-0.10.2.dev8.dist-info/WHEEL,sha256=bhMFZwp6VMtrbl2Ck6PlXryKaCggO1NzYn_HcFbBF1I,97
|
|
157
|
+
managed_deepagents-0.10.2.dev8.dist-info/entry_points.txt,sha256=ziZqkKuaDO3qHCjKmBhrx9cm3ok8bZ9xcEDpUTj4unM,53
|
|
158
|
+
managed_deepagents-0.10.2.dev8.dist-info/top_level.txt,sha256=fdBo4O0Hlol_w022tTLB5ftZpamb4yJoQ3MUvjgTGfA,19
|
|
159
|
+
managed_deepagents-0.10.2.dev8.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{managed_deepagents-0.10.2.dev6.dist-info → managed_deepagents-0.10.2.dev8.dist-info}/top_level.txt
RENAMED
|
File without changes
|