Coverage for apps / backend / src / orcheo_backend / app / mcp_server / email_tools.py: 99%
170 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
1"""Workspace email MCP tools backed by encrypted Orcheo vault credentials."""
3from __future__ import annotations
4import asyncio
5import inspect
6from datetime import UTC, datetime, timedelta
7from typing import Any, Literal
8from fastmcp import FastMCP
9from fastmcp.apps import AppConfig
10from fastmcp.exceptions import ToolError
11from fastmcp.server.dependencies import get_http_request
12from fastmcp.tools import ToolResult
13from pydantic import BaseModel, Field
14from orcheo.vault import DuplicateCredentialNameError, VaultError
15from orcheo_backend.app.authentication import (
16 PREAUTHENTICATED_SCOPE_KEY,
17 RequestContext,
18)
19from orcheo_backend.app.dependencies import get_vault
20from orcheo_backend.app.errors import WorkspaceQuotaExceededError
21from orcheo_backend.app.mcp_server._shared import (
22 DESTRUCTIVE,
23 READ_ONLY,
24 WRITE,
25 WorkspaceArg,
26 api_client,
27 caller_subject,
28)
29from orcheo_backend.app.mcp_server.app_tools import load_view
30from orcheo_backend.app.mcp_server.email_client import (
31 EmailAccounts,
32 EmailAccountSave,
33 TestEmailAccount,
34)
35from orcheo_backend.app.mcp_server.email_errors import ServiceError
36from orcheo_backend.app.mcp_server.email_mail import TOOL_SPECS
37from orcheo_backend.app.mcp_server.form_tokens import (
38 FORM_TOKEN_META_KEY,
39 CredentialForm,
40 issue_form_token,
41 verify_form_token,
42)
43from orcheo_backend.app.mcp_server.scopes import requires
44from orcheo_backend.app.workspace import get_workspace_repository
45from orcheo_backend.app.workspace_governance import ensure_workspace_credential_quota
48EMAIL_FORM_URI = "ui://orcheo/email-account-form"
49EMAIL_ACCOUNT_SETTINGS_META_KEY = "orcheo/emailAccountSettings"
50SCHEDULE_HORIZON = timedelta(days=30)
53class _FormTokenArgs(BaseModel):
54 form_token: str
57class _FormSave(EmailAccountSave):
58 form_token: str
61class _FormAccount(_FormTokenArgs):
62 account_id: str = Field(min_length=1, max_length=200)
65class _FormAccountTest(_FormAccount):
66 protocol: Literal["imap", "smtp", "both"] = "both"
69def _client_id(context: RequestContext) -> str | None:
70 value = context.claims.get("client_id") 1agefdbc
71 return value if isinstance(value, str) else None 1agefdbc
74def _request_context() -> RequestContext:
75 context = get_http_request().scope.get(PREAUTHENTICATED_SCOPE_KEY) 1agehfdbc
76 if not isinstance(context, RequestContext) or not context.is_authenticated: 1agehfdbc
77 raise ToolError("Sign in to use email tools.") 1h
78 return context 1agefdbc
81async def _manager(
82 workspace: str | None = None,
83) -> tuple[EmailAccounts, dict[str, Any]]:
84 async with api_client(workspace) as api: 1aiehfdbc
85 active = await api.get("/api/workspaces/active") 1aiehfdbc
86 return ( 1aiehfdbc
87 EmailAccounts(get_vault(), str(active["workspace_id"]), actor=caller_subject()),
88 active,
89 )
92async def _verify_form(
93 token: str, *, workspace: str | None = None
94) -> tuple[EmailAccounts, CredentialForm]:
95 context = _request_context() 1agehfdbc
96 form = verify_form_token( 1agefdbc
97 token,
98 subject=context.subject,
99 client_id=_client_id(context),
100 purpose="email_account",
101 )
102 async with api_client(form.workspace or workspace) as api: 1agefdbc
103 active = await api.get("/api/workspaces/active") 1agefdbc
104 if form.workspace_id != str(active["workspace_id"]): 1agefdbc
105 raise ToolError("The form's workspace has changed. Open a new one.") 1g
106 return ( 1aefdbc
107 EmailAccounts(get_vault(), str(active["workspace_id"]), actor=caller_subject()),
108 form,
109 )
112def _function_signature(model: type[BaseModel]) -> inspect.Signature:
113 params: list[inspect.Parameter] = [] 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
114 for name, field in model.model_fields.items(): 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
115 default = field.default 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
116 if field.is_required(): 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
117 default = inspect.Parameter.empty 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
118 elif field.default_factory is not None: 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
119 default = field.get_default(call_default_factory=True) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
120 params.append( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
121 inspect.Parameter(
122 name,
123 inspect.Parameter.KEYWORD_ONLY,
124 default=default,
125 annotation=field.rebuild_annotation(),
126 )
127 )
128 params.append( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
129 inspect.Parameter(
130 "workspace",
131 inspect.Parameter.KEYWORD_ONLY,
132 default=None,
133 annotation=WorkspaceArg,
134 )
135 )
136 return inspect.Signature(params, return_annotation=Any) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
139def _register_model_tool(
140 server: FastMCP,
141 *,
142 name: str,
143 title: str,
144 description: str,
145 model: type[BaseModel],
146 access: str,
147 scope: str | None = None,
148 destructive: bool = False,
149 app_only: bool = False,
150 handler: Any = None,
151) -> None:
152 """Register one email tool.
154 ``access`` picks the tool's annotations; ``scope`` the OAuth scope it sits
155 behind, which defaults to ``email:{access}`` and is given explicitly only
156 where a read-only tool belongs to a flow gated by a wider scope.
157 """
159 async def invoke(**kwargs: Any) -> Any: 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
160 workspace = kwargs.pop("workspace", None) 1agiehfdbc
161 try: 1agiehfdbc
162 data = model.model_validate(kwargs).model_dump(mode="python") 1agiehfdbc
163 if handler is not None: 1agiehfdbc
164 return await handler(data, workspace) 1agehfdbc
165 manager, _ = await _manager(workspace) 1ib
166 actor = caller_subject() 1ib
167 return await asyncio.to_thread(_dispatch, manager, name, data, actor) 1ib
168 except ServiceError as error: 1agihbc
169 raise ToolError(error.message) from error 1bc
170 except WorkspaceQuotaExceededError as error: 1agihbc
171 raise ToolError(error.message) from error 1b
172 except VaultError as error: 1agihbc
173 # A mailbox or message removed mid-request: say so without vault detail.
174 raise ToolError( 1i
175 "Stored email settings changed during this request. Try again."
176 ) from error
177 except ValueError as error: 1aghbc
178 raise ToolError(str(error)) from error 1b
180 invoke.__name__ = name 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
181 invoke.__doc__ = description 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
182 signature = _function_signature(model) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
183 invoke.__signature__ = signature # type: ignore[attr-defined] 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
184 invoke.__annotations__ = { 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
185 **{param.name: param.annotation for param in signature.parameters.values()},
186 "return": signature.return_annotation,
187 }
188 annotations = ( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
189 DESTRUCTIVE if destructive else WRITE if access == "write" else READ_ONLY
190 )
191 app: AppConfig | None = None 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
192 if app_only: 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
193 app = AppConfig(resource_uri=EMAIL_FORM_URI, visibility=["app"]) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
194 server.tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
195 name=name,
196 title=title,
197 description=description,
198 annotations=annotations,
199 tags=requires(scope or f"email:{access}"),
200 app=app,
201 )(invoke)
204def _dispatch(
205 accounts: EmailAccounts,
206 name: str,
207 data: dict[str, Any],
208 actor: str,
209) -> dict[str, Any]:
210 operations = { 2i b 1b2b3b4b5b6b7b8bZb9b!b#b$b%b'b(b)bVb*b+b0b
211 "search_emails": lambda: accounts.search(actor, data),
212 "get_email": lambda: accounts.get_email(
213 actor,
214 data["message_id"],
215 include_html=data["include_html"],
216 max_body_chars=data["max_body_chars"],
217 ),
218 "download_email_attachment": lambda: accounts.download_attachment(
219 actor, data["attachment_id"]
220 ),
221 "send_email": lambda: accounts.run_idempotently(
222 actor,
223 "send_email",
224 data,
225 lambda send_data: _send_message(accounts, actor, send_data),
226 ),
227 "mark_emails_read": lambda: accounts.mark_read(
228 actor, data["message_ids"], True
229 ),
230 "mark_emails_unread": lambda: accounts.mark_read(
231 actor, data["message_ids"], False
232 ),
233 "manage_email_messages": lambda: accounts.manage_messages(actor, data),
234 "list_email_folders": lambda: accounts.list_folders(actor, data["account_id"]),
235 "reply_to_email": lambda: accounts.reply(actor, data["message_id"], data),
236 "forward_email": lambda: accounts.forward(actor, data["message_id"], data),
237 "save_email_draft": lambda: accounts.run_idempotently(
238 actor,
239 "save_email_draft",
240 data,
241 lambda draft_data: accounts.save_draft(actor, draft_data),
242 ),
243 "send_email_draft": lambda: accounts.send_draft(actor, data["message_id"]),
244 "get_email_thread": lambda: accounts.thread(
245 actor, data["message_id"], data["limit"]
246 ),
247 "read_email_attachment": lambda: accounts.attachment_text(
248 actor, data["attachment_id"], data["max_chars"]
249 ),
250 "respond_to_email_invitation": lambda: accounts.respond_to_invite(
251 actor, data["message_id"], data["response"], data["comment"]
252 ),
253 "get_email_event_details": lambda: accounts.event_links(
254 actor, data["message_id"]
255 ),
256 "find_email_contacts": lambda: accounts.find_contacts(
257 actor, data["account_id"], data["query"], data["limit"]
258 ),
259 "list_scheduled_emails": lambda: _list_scheduled(accounts, actor),
260 "cancel_scheduled_email": lambda: accounts.cancel_scheduled(
261 actor, data["scheduled_id"]
262 ),
263 "set_default_email_account": lambda: accounts.set_default(
264 actor, data["account_id"]
265 ),
266 }
267 try: 2i b 1b2b3b4b5b6b7b8bZb9b!b#b$b%b'b(b)bVb*b+b0b
268 operation = operations[name] 2i b 1b2b3b4b5b6b7b8bZb9b!b#b$b%b'b(b)bVb*b+b0b
269 except KeyError as error: 20b
270 raise ToolError(f"Unknown email operation: {name}") from error 20b
271 return operation() 2i b 1b2b3b4b5b6b7b8bZb9b!b#b$b%b'b(b)bVb*b+b
274def _send_message(
275 accounts: EmailAccounts, actor: str, data: dict[str, Any]
276) -> dict[str, Any]:
277 send_at = data.get("send_at") 2b ,bWbXbYbVb
278 if not send_at: 2b ,bWbXbYbVb
279 return accounts.send(actor, data) 2b ,bVb
280 parsed = datetime.fromisoformat(send_at.replace("Z", "+00:00")).astimezone(UTC) 2WbXbYb
281 now = datetime.now(UTC) 2WbXbYb
282 if parsed <= now or parsed > now + SCHEDULE_HORIZON: 2WbXbYb
283 raise ServiceError( 2XbYb
284 "email.invalid_send_at", "Schedule between now and 30 days ahead.", 400
285 )
286 return accounts.schedule(actor, data, parsed.isoformat()) 2Wb
289def _list_scheduled(accounts: EmailAccounts, actor: str) -> dict[str, Any]:
290 return {"scheduled": accounts.list_scheduled(actor)} 2i b Zb
293def _register_account_tools(server: FastMCP) -> None:
294 @server.resource( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
295 EMAIL_FORM_URI,
296 name="email_account_form",
297 title="Orcheo email account",
298 app=AppConfig(prefers_border=True),
299 )
300 def email_account_form() -> str: 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
301 return load_view("email_account_form.html") 1e
303 @server.tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
304 annotations=READ_ONLY,
305 app=AppConfig(resource_uri=EMAIL_FORM_URI, prefers_border=True),
306 tags=requires("email:write"),
307 )
308 async def open_email_settings( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
309 account_id: str | None = None,
310 workspace: WorkspaceArg = None,
311 ) -> ToolResult:
312 """Open the private form for managing encrypted mailbox settings."""
313 accounts, active = await _manager(workspace) 1aehfdbc
314 public_accounts = await asyncio.to_thread( 1aehfdbc
315 accounts.list_agent_accounts, caller_subject()
316 )
317 if account_id is not None and not any( 1aehfdbc
318 item["account_id"] == account_id for item in public_accounts
319 ):
320 raise ToolError("Email account not found.") 1e
321 context = _request_context() 1aehfdbc
322 token = issue_form_token( 1aefdbc
323 CredentialForm(
324 subject=context.subject,
325 client_id=_client_id(context),
326 workspace=active["slug"],
327 workspace_id=str(active["workspace_id"]),
328 credential_id=None, # The form can switch between workspace mailboxes.
329 purpose="email_account",
330 )
331 )
332 return ToolResult( 1aefdbc
333 content=(
334 "Opened the private email account form. Mailbox passwords are "
335 "entered directly into the Orcheo credential vault."
336 ),
337 structured_content={"accounts": public_accounts, "account_id": account_id},
338 meta={FORM_TOKEN_META_KEY: token},
339 )
341 @server.tool(annotations=READ_ONLY, tags=requires("email:accounts:read")) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
342 async def list_email_accounts(workspace: WorkspaceArg = None) -> dict[str, Any]: 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
343 """List linked email accounts without server settings or passwords."""
344 accounts, _ = await _manager(workspace) 1e
345 public_accounts = await asyncio.to_thread( 1e
346 accounts.list_agent_accounts, caller_subject()
347 )
348 return {"accounts": public_accounts} 1e
350 _register_private_account_actions(server) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
353def _register_private_account_actions(server: FastMCP) -> None: # noqa: C901
354 async def get_settings(data: dict[str, Any], workspace: str | None) -> ToolResult: 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
355 manager, form = await _verify_form(data["form_token"], workspace=workspace) 1adc
356 if form.credential_id and form.credential_id != data["account_id"]: 1adc
357 raise ToolError("This form is bound to another email account.") 1a
358 account = await asyncio.to_thread( 1adc
359 manager.get_account_settings, caller_subject(), data["account_id"]
360 )
361 return ToolResult( 1adc
362 content=(
363 "Loaded mailbox settings. Password fields are blank because saved "
364 "passwords cannot be recovered."
365 ),
366 structured_content={"account": account},
367 meta={EMAIL_ACCOUNT_SETTINGS_META_KEY: {"account": account}},
368 )
370 async def save_account( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
371 data: dict[str, Any], workspace: str | None
372 ) -> dict[str, Any]:
373 manager, form = await _verify_form(data.pop("form_token"), workspace=workspace) 1agehfdbc
374 if form.credential_id and form.credential_id != data.get("account_id"): 1aefdbc
375 raise ToolError("This form is bound to another email account.") 1a
376 if not data.get("account_id"): 376 ↛ 381line 376 didn't jump to line 381 because the condition on line 376 was always true1aefdbc
377 workspace_record = await asyncio.to_thread( 1aefdbc
378 get_workspace_repository().get_workspace, manager.workspace_uuid
379 )
380 await ensure_workspace_credential_quota(manager.vault, workspace_record) 1aefdbc
381 try: 1aefdc
382 account = await asyncio.to_thread( 1aefdc
383 manager.save_account, caller_subject(), data
384 )
385 except DuplicateCredentialNameError as error: 1c
386 raise ToolError( 1c
387 "That mailbox address is already in use in this workspace."
388 ) from error
389 return {"saved": True, "account": account} 1aefdc
391 async def test_account( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
392 data: dict[str, Any], workspace: str | None
393 ) -> dict[str, Any]:
394 manager, form = await _verify_form(data["form_token"], workspace=workspace) 1afd
395 if form.credential_id and form.credential_id != data["account_id"]: 1afd
396 raise ToolError("This form is bound to another email account.") 1a
397 parsed = TestEmailAccount( 1fd
398 account_id=data["account_id"], protocol=data["protocol"]
399 )
400 return await asyncio.to_thread( 1fd
401 manager.test_account, caller_subject(), parsed.account_id, parsed.protocol
402 )
404 async def delete_account( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
405 data: dict[str, Any], workspace: str | None
406 ) -> dict[str, Any]:
407 manager, form = await _verify_form(data["form_token"], workspace=workspace) 1adc
408 if form.credential_id and form.credential_id != data["account_id"]: 1adc
409 raise ToolError("This form is bound to another email account.") 1a
410 return await asyncio.to_thread( 1dc
411 manager.delete_account, caller_subject(), data["account_id"]
412 )
414 _register_model_tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
415 server,
416 name="get_email_account_settings",
417 title="Load email account settings",
418 description="Load non-secret mailbox settings in the private form.",
419 model=_FormAccount,
420 access="read",
421 # Read-only, but reachable only through the ``email:write`` form that
422 # issues its token, so it sits behind that scope rather than
423 # ``email:read``: a client granted mailbox management but not mail
424 # reading must still be able to load settings into the form.
425 scope="email:write",
426 app_only=True,
427 handler=get_settings,
428 )
429 _register_model_tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
430 server,
431 name="save_email_account",
432 title="Save an email account",
433 description=(
434 "Save mailbox settings and encrypted SMTP and IMAP passwords to the "
435 "Orcheo vault."
436 ),
437 model=_FormSave,
438 access="write",
439 app_only=True,
440 handler=save_account,
441 )
442 _register_model_tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
443 server,
444 name="test_email_account",
445 title="Test an email account connection",
446 description="Test the selected mailbox's IMAP, SMTP, or both connections.",
447 model=_FormAccountTest,
448 access="write",
449 app_only=True,
450 handler=test_account,
451 )
452 _register_model_tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
453 server,
454 name="delete_email_account",
455 title="Remove an email account",
456 description="Remove a linked mailbox and its encrypted vault credential.",
457 model=_FormAccount,
458 access="write",
459 destructive=True,
460 app_only=True,
461 handler=delete_account,
462 )
465def register_email_tools(server: FastMCP) -> None:
466 """Register all generic email client and account management tools."""
467 _register_account_tools(server) 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
468 for name, ( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
469 title,
470 description,
471 model,
472 access,
473 destructive,
474 ) in TOOL_SPECS.items():
475 _register_model_tool( 2k l m n o p q r s t u v w x y z a g i e h f d b c A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % ' ( ) * + , - . / : ; = ? @ [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbGbHbIbJbKbLbMbNbObPbQbRbSbTbUb
476 server,
477 name=name,
478 title=title,
479 description=description,
480 model=model,
481 access=access,
482 destructive=destructive,
483 )
486__all__ = ["EMAIL_FORM_URI", "register_email_tools"]