hoja-cli 0.21.4__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.
- VERSION +1 -0
- google_workspace/__init__.py +19 -0
- google_workspace/client.py +253 -0
- google_workspace/config.py +39 -0
- google_workspace/errors.py +19 -0
- google_workspace/mcp_server.py +100 -0
- google_workspace/oauth.py +131 -0
- google_workspace/principal.py +83 -0
- google_workspace/py.typed +0 -0
- google_workspace/tools.py +64 -0
- google_workspace/writes.py +44 -0
- hoja/__init__.py +29 -0
- hoja/__main__.py +6 -0
- hoja/auth.py +42 -0
- hoja/cli.py +161 -0
- hoja/cli_state.py +55 -0
- hoja/client.py +268 -0
- hoja/commands/__init__.py +4 -0
- hoja/commands/auth_cmd.py +271 -0
- hoja/commands/comment.py +149 -0
- hoja/commands/cycle.py +75 -0
- hoja/commands/init.py +108 -0
- hoja/commands/issue.py +398 -0
- hoja/commands/label.py +163 -0
- hoja/commands/memory.py +240 -0
- hoja/commands/project.py +56 -0
- hoja/commands/raw.py +50 -0
- hoja/commands/team.py +102 -0
- hoja/commands/update.py +162 -0
- hoja/config.py +362 -0
- hoja/errors.py +107 -0
- hoja/filters.py +150 -0
- hoja/graphql/__init__.py +5 -0
- hoja/graphql/fragments.py +138 -0
- hoja/graphql/mutations.py +160 -0
- hoja/graphql/queries.py +245 -0
- hoja/mcp/__init__.py +27 -0
- hoja/mcp/content.py +151 -0
- hoja/mcp/prompts.py +298 -0
- hoja/mcp/resources.py +213 -0
- hoja/mcp/server.py +189 -0
- hoja/memory_board.py +370 -0
- hoja/models/__init__.py +37 -0
- hoja/models/base.py +64 -0
- hoja/models/cycle.py +32 -0
- hoja/models/enums.py +62 -0
- hoja/models/issue.py +99 -0
- hoja/models/label.py +17 -0
- hoja/models/project.py +60 -0
- hoja/models/team.py +31 -0
- hoja/models/user.py +32 -0
- hoja/models/workflow.py +65 -0
- hoja/output.py +410 -0
- hoja/skill_content/commands.md +222 -0
- hoja/skill_content/examples.md +193 -0
- hoja/skill_content/filters.md +101 -0
- hoja/skill_content/output-formats.md +92 -0
- hoja/skill_content/overview.md +123 -0
- hoja/skill_content/workflows.md +174 -0
- hoja_cli-0.21.4.dist-info/METADATA +279 -0
- hoja_cli-0.21.4.dist-info/RECORD +107 -0
- hoja_cli-0.21.4.dist-info/WHEEL +4 -0
- hoja_cli-0.21.4.dist-info/entry_points.txt +4 -0
- hoja_cli-0.21.4.dist-info/licenses/LICENSE +21 -0
- hoja_server/README.md +135 -0
- hoja_server/__init__.py +11 -0
- hoja_server/abac.py +116 -0
- hoja_server/agent_chat.py +280 -0
- hoja_server/agent_conversations.py +91 -0
- hoja_server/agent_durable.py +332 -0
- hoja_server/agent_prompt.py +117 -0
- hoja_server/agent_threads.py +96 -0
- hoja_server/agent_uploads.py +60 -0
- hoja_server/app.py +2189 -0
- hoja_server/cadence.py +231 -0
- hoja_server/cli.py +191 -0
- hoja_server/cloudflare_realtime.py +110 -0
- hoja_server/comment_policy.py +70 -0
- hoja_server/connector_actions.py +119 -0
- hoja_server/connectors_api.py +375 -0
- hoja_server/db.py +1816 -0
- hoja_server/denials.py +18 -0
- hoja_server/deployment.py +28 -0
- hoja_server/email_adapter.py +94 -0
- hoja_server/google_login.py +217 -0
- hoja_server/google_oidc.py +342 -0
- hoja_server/identity_transfer.py +210 -0
- hoja_server/mcp_oauth.py +623 -0
- hoja_server/mcp_tools.py +579 -0
- hoja_server/meeting_policy.py +179 -0
- hoja_server/meetings.py +1332 -0
- hoja_server/meetings_api.py +909 -0
- hoja_server/model_providers.py +205 -0
- hoja_server/realtime.py +690 -0
- hoja_server/resolvers.py +1281 -0
- hoja_server/schema.graphql +477 -0
- hoja_server/schema_sdl.py +8 -0
- hoja_server/secrets_box.py +39 -0
- hoja_server/signup_config.py +292 -0
- hoja_server/signup_gate.py +393 -0
- hoja_server/signup_policy.py +97 -0
- hoja_server/signup_store.py +577 -0
- hoja_server/store.py +2179 -0
- hoja_server/sync.py +249 -0
- hoja_server/tenant_context.py +131 -0
- hoja_server/turnstile.py +81 -0
- hoja_server/writer.py +1262 -0
hoja_server/mcp_tools.py
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
"""Agent-facing MCP tools generated from the Hoja GraphQL schema.
|
|
2
|
+
|
|
3
|
+
Each allowlisted GraphQL root field becomes one MCP tool with:
|
|
4
|
+
- a typed JSON input schema (GraphQL args; a single `input` object is flattened),
|
|
5
|
+
- friendly references (team keys, issue identifiers, "me"/emails/names, state,
|
|
6
|
+
label and project names) resolved to ids before execution,
|
|
7
|
+
- a server-chosen selection that returns the readable entity, so agents can
|
|
8
|
+
verify what they read or changed,
|
|
9
|
+
- specific errors (unknown args, missing scope, not found, invalid reference)
|
|
10
|
+
raised as ToolError so the SDK forwards the text to the model.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from graphql import (
|
|
22
|
+
GraphQLEnumType,
|
|
23
|
+
GraphQLError,
|
|
24
|
+
GraphQLInputObjectType,
|
|
25
|
+
GraphQLList,
|
|
26
|
+
GraphQLNonNull,
|
|
27
|
+
GraphQLObjectType,
|
|
28
|
+
GraphQLSchema,
|
|
29
|
+
Undefined,
|
|
30
|
+
execute,
|
|
31
|
+
parse,
|
|
32
|
+
validate,
|
|
33
|
+
)
|
|
34
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
35
|
+
from mcp.server.mcpserver.tools.base import Tool
|
|
36
|
+
from mcp.server.mcpserver.utilities.func_metadata import ArgModelBase, FuncMetadata
|
|
37
|
+
from mcp.types import ToolAnnotations
|
|
38
|
+
from pydantic import ConfigDict
|
|
39
|
+
|
|
40
|
+
from hoja_server.denials import DENY_HINT
|
|
41
|
+
|
|
42
|
+
log = logging.getLogger("hoja.mcp")
|
|
43
|
+
|
|
44
|
+
READ_TOOLS: dict[str, str] = {
|
|
45
|
+
"viewer": "The signed-in user (id, name, email, admin).",
|
|
46
|
+
"workspace": "The current workspace (organization).",
|
|
47
|
+
"organizationMembers": "People in the workspace. Use to find someone before assigning.",
|
|
48
|
+
"teams": "Teams with their keys. Issue identifiers are TEAMKEY-N (e.g. ENG-12).",
|
|
49
|
+
"team": "One team by key or id, with its workflow states, members and active cycle.",
|
|
50
|
+
"issues": (
|
|
51
|
+
"List issues, newest first. Example filter: "
|
|
52
|
+
'{"team": {"key": {"eq": "ENG"}}, "state": {"type": {"nin": ["completed", "canceled"]}}}. '
|
|
53
|
+
"State types: backlog, unstarted, started, completed, canceled."
|
|
54
|
+
),
|
|
55
|
+
"issue": (
|
|
56
|
+
"One issue by identifier (ENG-12) or id, with state, assignee, labels, comments, "
|
|
57
|
+
"its parent and sub-issues in children."
|
|
58
|
+
),
|
|
59
|
+
"searchIssues": "Text search over issue titles, descriptions and identifiers.",
|
|
60
|
+
"myIssueActivity": "Recent activity on issues involving the signed-in user.",
|
|
61
|
+
"inboxNotifications": "The signed-in user's inbox notifications.",
|
|
62
|
+
"inboxUnreadCount": "Number of unread inbox notifications.",
|
|
63
|
+
"projects": "List projects.",
|
|
64
|
+
"project": "One project by id or name.",
|
|
65
|
+
"projectUpdates": "Status updates posted on projects.",
|
|
66
|
+
"initiatives": "List initiatives.",
|
|
67
|
+
"initiative": "One initiative by id.",
|
|
68
|
+
"workflowStates": "Workflow states. States are per team; filter with {\"team\": {\"key\": {\"eq\": \"ENG\"}}}.",
|
|
69
|
+
"cycles": "List cycles (sprints).",
|
|
70
|
+
"cycle": "One cycle by id.",
|
|
71
|
+
"teamCycleCadence": "Whether cycles are enabled for a team, plus its active and upcoming cycles.",
|
|
72
|
+
"issueLabels": "Issue labels (workspace-wide and per team).",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
WRITE_TOOLS: dict[str, str] = {
|
|
76
|
+
"issueCreate": (
|
|
77
|
+
"Create an issue. For multi-step work, create or reuse one parent issue, then create actionable "
|
|
78
|
+
"sub-issues with parentId instead of separate root issues; omit parentId for a standalone "
|
|
79
|
+
"issue or the parent itself. Returns the created issue including its identifier, parent and children."
|
|
80
|
+
),
|
|
81
|
+
"issueUpdate": (
|
|
82
|
+
"Update an issue: title, description, priority, state (by name), assignee "
|
|
83
|
+
"('me', email or name), project, cycle, labels, estimate, due date and parent. "
|
|
84
|
+
"parentId reparents an issue within its team; null detaches it from its parent. "
|
|
85
|
+
"Send ONLY the fields to change; every field you send is written (labelIds replaces all labels). "
|
|
86
|
+
"Returns the updated issue."
|
|
87
|
+
),
|
|
88
|
+
"issueArchive": "Archive an issue (reversible; prefer this over delete).",
|
|
89
|
+
"issueDelete": "Permanently delete an issue. Confirm with the user first.",
|
|
90
|
+
"commentCreate": "Add a comment to an issue.",
|
|
91
|
+
"commentUpdate": "Edit a comment.",
|
|
92
|
+
"commentDelete": "Delete a comment.",
|
|
93
|
+
"issueLabelCreate": "Create a label, optionally scoped to a team.",
|
|
94
|
+
"issueLabelUpdate": "Rename or recolor a label.",
|
|
95
|
+
"issueLabelDelete": "Delete a label.",
|
|
96
|
+
"projectCreate": "Create a project, optionally linked to teams.",
|
|
97
|
+
"projectUpdate": "Update a project.",
|
|
98
|
+
"projectArchive": "Archive a project.",
|
|
99
|
+
"projectUpdateCreate": "Post a status update on a project.",
|
|
100
|
+
"initiativeCreate": "Create an initiative.",
|
|
101
|
+
"initiativeUpdate": "Update an initiative.",
|
|
102
|
+
"initiativeArchive": "Archive an initiative.",
|
|
103
|
+
"attachmentCreate": "Attach a link to an issue.",
|
|
104
|
+
"teamCreate": "Create a team.",
|
|
105
|
+
"teamUpdate": "Rename a team or change its key or description.",
|
|
106
|
+
"teamArchive": "Archive a team.",
|
|
107
|
+
"teamMemberAdd": "Add a workspace member to a team (admin only).",
|
|
108
|
+
"teamMemberRemove": "Remove a member from a team (admin only).",
|
|
109
|
+
"teamCycleCadenceEnable": "Enable weekly cycles for a team (admin only). weekday: 0=Monday ... 6=Sunday.",
|
|
110
|
+
"notificationMarkRead": "Mark an inbox notification read.",
|
|
111
|
+
"notificationArchive": "Archive an inbox notification.",
|
|
112
|
+
"notificationMarkAllRead": "Mark every inbox notification read.",
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
DESTRUCTIVE = {"issueDelete", "commentDelete", "issueLabelDelete", "teamMemberRemove",
|
|
116
|
+
"issueArchive", "projectArchive", "initiativeArchive", "teamArchive"}
|
|
117
|
+
IDEMPOTENT_PREFIXES = ("notificationMark", "notificationArchive")
|
|
118
|
+
|
|
119
|
+
FIELD_HINTS = {
|
|
120
|
+
"teamId": "Team key (e.g. \"ENG\") or id.",
|
|
121
|
+
"teamIds": "Team keys or ids.",
|
|
122
|
+
"stateId": "Workflow state name (e.g. \"In Progress\") or id. States belong to the issue's team.",
|
|
123
|
+
"assigneeId": "\"me\", an email, an exact member name, or a user id.",
|
|
124
|
+
"leadId": "\"me\", an email, an exact member name, or a user id.",
|
|
125
|
+
"ownerId": "\"me\", an email, an exact member name, or a user id.",
|
|
126
|
+
"userId": "\"me\", an email, an exact member name, or a user id.",
|
|
127
|
+
"labelIds": "Label names or ids. Replaces the issue's labels.",
|
|
128
|
+
"projectId": "Project name or id.",
|
|
129
|
+
"projectIds": "Project names or ids.",
|
|
130
|
+
"issueId": "Issue identifier (e.g. ENG-12) or id.",
|
|
131
|
+
"parentId": "Parent issue identifier (e.g. ENG-12) or id. Must be in the same team; null detaches.",
|
|
132
|
+
"priority": "1 urgent, 2 high, 3 medium, 4 low (or those names). On updates use \"none\" to clear; 0 is ignored.",
|
|
133
|
+
"first": "Page size.",
|
|
134
|
+
"after": "Cursor from a previous pageInfo.endCursor.",
|
|
135
|
+
"dueDate": "ISO-8601 date-time.",
|
|
136
|
+
}
|
|
137
|
+
ID_HINTS = {
|
|
138
|
+
"issue": "Issue identifier (e.g. ENG-12) or id.",
|
|
139
|
+
"team": "Team key (e.g. ENG) or id.",
|
|
140
|
+
"project": "Project name or id.",
|
|
141
|
+
"issueLabel": "Label name or id.",
|
|
142
|
+
}
|
|
143
|
+
PRIORITY_NAMES = {"none": 0, "no priority": 0, "urgent": 1, "high": 2, "medium": 3, "normal": 3, "low": 4}
|
|
144
|
+
|
|
145
|
+
_SCALARS = {
|
|
146
|
+
"String": {"type": "string"}, "ID": {"type": "string"}, "Int": {"type": "integer"},
|
|
147
|
+
"Float": {"type": "number"}, "Boolean": {"type": "boolean"},
|
|
148
|
+
"DateTime": {"type": "string", "description": "ISO-8601 date-time."},
|
|
149
|
+
"TimelessDate": {"type": "string", "description": "YYYY-MM-DD."},
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
# Readable fields kept when an object is referenced from another one.
|
|
153
|
+
_REF_FIELDS = ("id", "identifier", "key", "name", "displayName", "email", "title", "type",
|
|
154
|
+
"number", "startsAt", "endsAt", "status", "state", "priorityLabel", "body", "url")
|
|
155
|
+
# Noisy fields dropped from list rows.
|
|
156
|
+
_ROW_SKIP = {"description", "branchName", "avatarUrl", "color", "icon", "statusEmoji",
|
|
157
|
+
"statusLabel", "position", "changes"}
|
|
158
|
+
# Never selected: credentials and noisy relations.
|
|
159
|
+
_NEVER = {"apiKey", "secret", "inviteCode", "activity", "subscribers"}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _named(t):
|
|
163
|
+
while isinstance(t, (GraphQLNonNull, GraphQLList)):
|
|
164
|
+
t = t.of_type
|
|
165
|
+
return t
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _is_object(t) -> bool:
|
|
169
|
+
return isinstance(_named(t), GraphQLObjectType)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _is_connection(t) -> bool:
|
|
173
|
+
n = _named(t)
|
|
174
|
+
return isinstance(n, GraphQLObjectType) and "nodes" in n.fields and "pageInfo" in n.fields
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _usable(field) -> bool:
|
|
178
|
+
return not any(isinstance(a.type, GraphQLNonNull) and a.default_value is Undefined for a in field.args.values())
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _selection(t, level: str) -> str:
|
|
182
|
+
"""level: ref (identity only), row (list item), full (single entity)."""
|
|
183
|
+
obj = _named(t)
|
|
184
|
+
parts: list[str] = []
|
|
185
|
+
for name, field in obj.fields.items():
|
|
186
|
+
if name in _NEVER or not _usable(field):
|
|
187
|
+
continue
|
|
188
|
+
if not _is_object(field.type):
|
|
189
|
+
if level == "ref" and name not in _REF_FIELDS:
|
|
190
|
+
continue
|
|
191
|
+
if level == "row" and name in _ROW_SKIP:
|
|
192
|
+
continue
|
|
193
|
+
parts.append(name)
|
|
194
|
+
elif level == "ref":
|
|
195
|
+
continue
|
|
196
|
+
elif _is_connection(field.type):
|
|
197
|
+
if level == "full":
|
|
198
|
+
inner = _selection(_named(field.type).fields["nodes"].type, "row")
|
|
199
|
+
if inner:
|
|
200
|
+
parts.append(f"{name} {{ nodes {{ {inner} }} }}")
|
|
201
|
+
else:
|
|
202
|
+
inner = _selection(field.type, "ref")
|
|
203
|
+
if inner:
|
|
204
|
+
parts.append(f"{name} {{ {inner} }}")
|
|
205
|
+
if not parts and level == "ref":
|
|
206
|
+
leaves = [n for n, f in obj.fields.items() if not _is_object(f.type) and n not in _NEVER]
|
|
207
|
+
parts = leaves[:1]
|
|
208
|
+
return " ".join(parts)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _root_selection(field) -> str:
|
|
212
|
+
t = field.type
|
|
213
|
+
if not _is_object(t):
|
|
214
|
+
return ""
|
|
215
|
+
if _is_connection(t):
|
|
216
|
+
rows = _selection(_named(t).fields["nodes"].type, "row")
|
|
217
|
+
return f"{{ nodes {{ {rows} }} pageInfo {{ hasNextPage endCursor }} }}"
|
|
218
|
+
obj = _named(t)
|
|
219
|
+
if "success" in obj.fields: # mutation payload: success + affected entity
|
|
220
|
+
parts = ["success"]
|
|
221
|
+
for name, sub in obj.fields.items():
|
|
222
|
+
if name == "success" or name in _NEVER:
|
|
223
|
+
continue
|
|
224
|
+
if _is_object(sub.type):
|
|
225
|
+
parts.append(f"{name} {{ {_selection(sub.type, 'full')} }}")
|
|
226
|
+
else:
|
|
227
|
+
parts.append(name)
|
|
228
|
+
return "{ " + " ".join(parts) + " }"
|
|
229
|
+
level = "row" if isinstance(t, GraphQLList) or (isinstance(t, GraphQLNonNull) and isinstance(t.of_type, GraphQLList)) else "full"
|
|
230
|
+
return "{ " + _selection(t, level) + " }"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _json_schema(t, defs: dict) -> dict:
|
|
234
|
+
if isinstance(t, GraphQLNonNull):
|
|
235
|
+
return _json_schema(t.of_type, defs)
|
|
236
|
+
if isinstance(t, GraphQLList):
|
|
237
|
+
return {"type": "array", "items": _json_schema(t.of_type, defs)}
|
|
238
|
+
if isinstance(t, GraphQLEnumType):
|
|
239
|
+
return {"type": "string", "enum": list(t.values)}
|
|
240
|
+
if isinstance(t, GraphQLInputObjectType):
|
|
241
|
+
if t.name not in defs:
|
|
242
|
+
defs[t.name] = {} # placeholder for recursive inputs
|
|
243
|
+
props, required = {}, []
|
|
244
|
+
for fname, f in t.fields.items():
|
|
245
|
+
props[fname] = _json_schema(f.type, defs)
|
|
246
|
+
if isinstance(f.type, GraphQLNonNull) and f.default_value is Undefined:
|
|
247
|
+
required.append(fname)
|
|
248
|
+
defs[t.name] = {"type": "object", "properties": props, "additionalProperties": False,
|
|
249
|
+
**({"required": required} if required else {})}
|
|
250
|
+
return {"$ref": f"#/$defs/{t.name}"}
|
|
251
|
+
return dict(_SCALARS.get(getattr(t, "name", ""), {}))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _entity_of(op: str) -> str | None:
|
|
255
|
+
for prefix in ("issueLabel", "issue", "team", "project"):
|
|
256
|
+
if op.startswith(prefix):
|
|
257
|
+
return prefix
|
|
258
|
+
return None
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class _RawArgs(ArgModelBase):
|
|
262
|
+
"""Accept any JSON object; validation happens against the GraphQL types."""
|
|
263
|
+
|
|
264
|
+
model_config = ConfigDict(extra="allow")
|
|
265
|
+
|
|
266
|
+
def model_dump_one_level(self) -> dict[str, Any]:
|
|
267
|
+
return {"args": dict(self.model_extra or {})}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _prune(value):
|
|
271
|
+
"""Drop placeholder values some clients send for every optional field.
|
|
272
|
+
|
|
273
|
+
Removes "", [] and {} and comparator objects with eq == neq, which can never match.
|
|
274
|
+
"""
|
|
275
|
+
if isinstance(value, dict):
|
|
276
|
+
pruned = {k: _prune(v) for k, v in value.items()}
|
|
277
|
+
pruned = {k: v for k, v in pruned.items() if v not in ("", [], {})}
|
|
278
|
+
if "eq" in pruned and "neq" in pruned and pruned["eq"] == pruned["neq"]:
|
|
279
|
+
return {}
|
|
280
|
+
return pruned
|
|
281
|
+
if isinstance(value, list):
|
|
282
|
+
return [_prune(v) for v in value]
|
|
283
|
+
return value
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class _Spec:
|
|
287
|
+
def __init__(self, schema: GraphQLSchema, op: str, write: bool, description: str):
|
|
288
|
+
self.op, self.write = op, write
|
|
289
|
+
self.field = schema.get_type("Mutation" if write else "Query").fields[op]
|
|
290
|
+
self.flat_input: GraphQLInputObjectType | None = None
|
|
291
|
+
input_arg = self.field.args.get("input")
|
|
292
|
+
if input_arg is not None and isinstance(_named(input_arg.type), GraphQLInputObjectType):
|
|
293
|
+
fields = _named(input_arg.type).fields
|
|
294
|
+
if not set(fields) & (set(self.field.args) - {"input"}):
|
|
295
|
+
self.flat_input = _named(input_arg.type)
|
|
296
|
+
|
|
297
|
+
defs: dict = {}
|
|
298
|
+
props, required = {}, []
|
|
299
|
+
entity = _entity_of(op)
|
|
300
|
+
for name, arg in self.field.args.items():
|
|
301
|
+
if name == "input" and self.flat_input is not None:
|
|
302
|
+
for fname, f in self.flat_input.fields.items():
|
|
303
|
+
props[fname] = _json_schema(f.type, defs)
|
|
304
|
+
if isinstance(input_arg.type, GraphQLNonNull) and isinstance(f.type, GraphQLNonNull):
|
|
305
|
+
required.append(fname)
|
|
306
|
+
continue
|
|
307
|
+
props[name] = _json_schema(arg.type, defs)
|
|
308
|
+
if isinstance(arg.type, GraphQLNonNull) and arg.default_value is Undefined:
|
|
309
|
+
required.append(name)
|
|
310
|
+
for name, schema_part in props.items():
|
|
311
|
+
hint = ID_HINTS.get(entity) if name == "id" and entity else FIELD_HINTS.get(name)
|
|
312
|
+
if name == "parentId" and schema_part.get("type") == "string":
|
|
313
|
+
# GraphQL accepts null to detach; validating MCP clients must accept it too.
|
|
314
|
+
schema_part["type"] = ["string", "null"]
|
|
315
|
+
if op in ("team", "teamCycleCadence", "teamCycleCadenceEnable") and name in ("id", "teamId"):
|
|
316
|
+
hint = ID_HINTS["team"]
|
|
317
|
+
if hint and "$ref" not in schema_part:
|
|
318
|
+
schema_part["description"] = hint
|
|
319
|
+
self.parameters = {"type": "object", "properties": props, "additionalProperties": False}
|
|
320
|
+
if required:
|
|
321
|
+
self.parameters["required"] = required
|
|
322
|
+
if defs:
|
|
323
|
+
self.parameters["$defs"] = defs
|
|
324
|
+
self.description = description
|
|
325
|
+
|
|
326
|
+
decls = ", ".join(f"$v_{n}: {a.type}" for n, a in self.field.args.items())
|
|
327
|
+
uses = ", ".join(f"{n}: $v_{n}" for n in self.field.args)
|
|
328
|
+
kind = "mutation" if write else "query"
|
|
329
|
+
self.query = (f"{kind} Hoja{('(' + decls + ')') if decls else ''} "
|
|
330
|
+
f"{{ {op}{('(' + uses + ')') if uses else ''} {_root_selection(self.field)} }}")
|
|
331
|
+
self.document = parse(self.query)
|
|
332
|
+
errors = validate(schema, self.document)
|
|
333
|
+
if errors: # a bug in selection generation; fail at startup, not per call
|
|
334
|
+
raise RuntimeError(f"MCP tool {op} has an invalid generated query: {errors[0].message}")
|
|
335
|
+
|
|
336
|
+
def assemble(self, args: dict) -> dict:
|
|
337
|
+
allowed = set(self.parameters["properties"]) | ({"input"} if self.flat_input else set())
|
|
338
|
+
unknown = sorted(set(args) - allowed)
|
|
339
|
+
if unknown:
|
|
340
|
+
raise ToolError(
|
|
341
|
+
f"Unknown argument(s) {', '.join(unknown)} for hoja_{self.op}. "
|
|
342
|
+
f"Valid arguments: {', '.join(sorted(self.parameters['properties'])) or '(none)'}."
|
|
343
|
+
)
|
|
344
|
+
flat = _prune(args)
|
|
345
|
+
if self.flat_input is not None and isinstance(flat.get("input"), dict):
|
|
346
|
+
flat = {**flat.pop("input"), **flat}
|
|
347
|
+
if self.op.endswith("Update"):
|
|
348
|
+
# Clients that fill every field send 0 for untouched numbers; clearing needs an explicit "none".
|
|
349
|
+
flat = {k: v for k, v in flat.items() if not (k in ("priority", "estimate") and v == 0 and v is not False)}
|
|
350
|
+
for key, value in list(flat.items()):
|
|
351
|
+
gtype = self._type_of(key)
|
|
352
|
+
if isinstance(value, str) and gtype is not None and (
|
|
353
|
+
isinstance(_named(gtype), GraphQLInputObjectType) or isinstance(_strip(gtype), GraphQLList)
|
|
354
|
+
):
|
|
355
|
+
with contextlib.suppress(ValueError):
|
|
356
|
+
flat[key] = json.loads(value)
|
|
357
|
+
if isinstance(flat.get("priority"), str):
|
|
358
|
+
p = flat["priority"].strip().lower()
|
|
359
|
+
flat["priority"] = int(p) if p.isdigit() else PRIORITY_NAMES.get(p, flat["priority"])
|
|
360
|
+
return flat
|
|
361
|
+
|
|
362
|
+
def _type_of(self, key: str):
|
|
363
|
+
if key in self.field.args:
|
|
364
|
+
return self.field.args[key].type
|
|
365
|
+
if self.flat_input is not None and key in self.flat_input.fields:
|
|
366
|
+
return self.flat_input.fields[key].type
|
|
367
|
+
return None
|
|
368
|
+
|
|
369
|
+
def variables(self, flat: dict) -> dict:
|
|
370
|
+
variables = {}
|
|
371
|
+
input_fields = {}
|
|
372
|
+
for key, value in flat.items():
|
|
373
|
+
if self.flat_input is not None and key in self.flat_input.fields and key not in self.field.args:
|
|
374
|
+
input_fields[key] = value
|
|
375
|
+
else:
|
|
376
|
+
variables["v_" + key] = value
|
|
377
|
+
if self.flat_input is not None and (input_fields or isinstance(self.field.args["input"].type, GraphQLNonNull)):
|
|
378
|
+
variables["v_input"] = input_fields
|
|
379
|
+
return variables
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _strip(t):
|
|
383
|
+
return t.of_type if isinstance(t, GraphQLNonNull) else t
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class _Resolver:
|
|
387
|
+
"""Map friendly references (keys, names, emails, 'me') to ids via the same GraphQL context."""
|
|
388
|
+
|
|
389
|
+
def __init__(self, run: Callable[[str, dict | None], dict], viewer_id: str):
|
|
390
|
+
self.run, self.viewer_id = run, viewer_id
|
|
391
|
+
self._cache: dict[str, list[dict]] = {}
|
|
392
|
+
|
|
393
|
+
def _list(self, key: str, query: str, variables: dict | None = None) -> list[dict]:
|
|
394
|
+
cache_key = key + json.dumps(variables or {}, sort_keys=True)
|
|
395
|
+
if cache_key not in self._cache:
|
|
396
|
+
data = self.run(query, variables)
|
|
397
|
+
node = next(iter(data.values())) if data else None
|
|
398
|
+
self._cache[cache_key] = (node or {}).get("nodes", []) if isinstance(node, dict) else []
|
|
399
|
+
return self._cache[cache_key]
|
|
400
|
+
|
|
401
|
+
@staticmethod
|
|
402
|
+
def _pick(kind: str, value: str, rows: list[dict], fields: tuple[str, ...], show: Callable[[dict], str]) -> str:
|
|
403
|
+
if any(r["id"] == value for r in rows):
|
|
404
|
+
return value
|
|
405
|
+
wanted = value.strip().lower()
|
|
406
|
+
hits = [r for r in rows if any(str(r.get(f) or "").lower() == wanted for f in fields)]
|
|
407
|
+
if len(hits) == 1:
|
|
408
|
+
return hits[0]["id"]
|
|
409
|
+
options = ", ".join(show(r) for r in rows[:25]) or "(none visible)"
|
|
410
|
+
if hits:
|
|
411
|
+
raise ToolError(f"'{value}' matches several {kind}s: {', '.join(show(r) for r in hits)}. Use an id.")
|
|
412
|
+
raise ToolError(f"No {kind} matches '{value}'. Available {kind}s: {options}.")
|
|
413
|
+
|
|
414
|
+
def team(self, value: str) -> str:
|
|
415
|
+
rows = self._list("teams", "{ teams(first: 250) { nodes { id key name } } }")
|
|
416
|
+
return self._pick("team", value, rows, ("key", "name"), lambda r: f"{r['key']} ({r['name']})")
|
|
417
|
+
|
|
418
|
+
def user(self, value: str) -> str:
|
|
419
|
+
if value.strip().lower() in ("me", "myself", "self", "viewer"):
|
|
420
|
+
return self.viewer_id
|
|
421
|
+
rows = self._list("users", "{ organizationMembers(first: 250) { nodes { id name displayName email } } }")
|
|
422
|
+
return self._pick("workspace member", value, rows, ("email", "name", "displayName"),
|
|
423
|
+
lambda r: f"{r.get('name')} <{r.get('email')}>")
|
|
424
|
+
|
|
425
|
+
def state(self, value: str, team_id: str | None) -> str:
|
|
426
|
+
if not team_id:
|
|
427
|
+
return value
|
|
428
|
+
rows = self._list("states", "query($t: ID) { workflowStates(filter: {team: {id: {eq: $t}}}) { nodes { id name type } } }",
|
|
429
|
+
{"t": team_id})
|
|
430
|
+
return self._pick("workflow state", value, rows, ("name",), lambda r: f"{r['name']} ({r['type']})")
|
|
431
|
+
|
|
432
|
+
def label(self, value: str) -> str:
|
|
433
|
+
rows = self._list("labels", "{ issueLabels(first: 250) { nodes { id name } } }")
|
|
434
|
+
return self._pick("label", value, rows, ("name",), lambda r: r["name"])
|
|
435
|
+
|
|
436
|
+
def project(self, value: str) -> str:
|
|
437
|
+
rows = self._list("projects", "{ projects(first: 250) { nodes { id name } } }")
|
|
438
|
+
return self._pick("project", value, rows, ("name",), lambda r: r["name"])
|
|
439
|
+
|
|
440
|
+
def issue_team(self, ident: str) -> str | None:
|
|
441
|
+
data = self.run("query($i: String!) { issue(id: $i) { team { id } } }", {"i": ident})
|
|
442
|
+
return ((data.get("issue") or {}).get("team") or {}).get("id")
|
|
443
|
+
|
|
444
|
+
def apply(self, op: str, flat: dict) -> dict:
|
|
445
|
+
out = dict(flat)
|
|
446
|
+
entity = _entity_of(op)
|
|
447
|
+
for key in ("teamId",):
|
|
448
|
+
if isinstance(out.get(key), str):
|
|
449
|
+
out[key] = self.team(out[key])
|
|
450
|
+
if isinstance(out.get("teamIds"), list):
|
|
451
|
+
out["teamIds"] = [self.team(v) for v in out["teamIds"]]
|
|
452
|
+
for key in ("assigneeId", "leadId", "ownerId", "userId"):
|
|
453
|
+
if isinstance(out.get(key), str):
|
|
454
|
+
out[key] = self.user(out[key])
|
|
455
|
+
if isinstance(out.get("projectId"), str):
|
|
456
|
+
out["projectId"] = self.project(out["projectId"])
|
|
457
|
+
if isinstance(out.get("projectIds"), list):
|
|
458
|
+
out["projectIds"] = [self.project(v) for v in out["projectIds"]]
|
|
459
|
+
if isinstance(out.get("labelIds"), list):
|
|
460
|
+
out["labelIds"] = [self.label(v) for v in out["labelIds"]]
|
|
461
|
+
if isinstance(out.get("id"), str):
|
|
462
|
+
if entity == "team" or op in ("teamCycleCadence",):
|
|
463
|
+
out["id"] = self.team(out["id"])
|
|
464
|
+
elif entity == "project" and op != "projectUpdateCreate":
|
|
465
|
+
out["id"] = self.project(out["id"])
|
|
466
|
+
elif entity == "issueLabel":
|
|
467
|
+
out["id"] = self.label(out["id"])
|
|
468
|
+
if isinstance(out.get("stateId"), str):
|
|
469
|
+
team_id = out.get("teamId") if op == "issueCreate" else (
|
|
470
|
+
self.issue_team(out["id"]) if op == "issueUpdate" and isinstance(out.get("id"), str) else None)
|
|
471
|
+
out["stateId"] = self.state(out["stateId"], team_id)
|
|
472
|
+
return out
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
_REF_HINTS = {
|
|
476
|
+
"teamId": "List teams with hoja_teams.",
|
|
477
|
+
"stateId": "See the team's states with hoja_team.",
|
|
478
|
+
"assigneeId": "List people with hoja_organizationMembers.",
|
|
479
|
+
"labelIds": "List labels with hoja_issueLabels; labels must belong to the issue's team or the workspace.",
|
|
480
|
+
"projectId": "List projects with hoja_projects.",
|
|
481
|
+
"parentId": "The parent must be an issue in the same team.",
|
|
482
|
+
"cycleId": "List cycles with hoja_cycles.",
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _error_text(op: str, errors: list[GraphQLError]) -> str:
|
|
487
|
+
messages = []
|
|
488
|
+
for err in errors:
|
|
489
|
+
original = err.original_error
|
|
490
|
+
if original is not None and not isinstance(original, (GraphQLError, ValueError)):
|
|
491
|
+
log.error("MCP tool %s failed", op, exc_info=original)
|
|
492
|
+
messages.append("internal error")
|
|
493
|
+
continue
|
|
494
|
+
message = err.message.replace("$v_", "$").replace("'v_", "'")
|
|
495
|
+
field = (err.extensions or {}).get("field")
|
|
496
|
+
if field and message == "Invalid reference":
|
|
497
|
+
message = f"Invalid reference in '{field}': it does not exist or is not visible to you."
|
|
498
|
+
if field in _REF_HINTS:
|
|
499
|
+
message += " " + _REF_HINTS[field]
|
|
500
|
+
elif field and field not in message:
|
|
501
|
+
message += f" (field: {field})"
|
|
502
|
+
messages.append(message)
|
|
503
|
+
text = f"hoja_{op} failed: " + "; ".join(dict.fromkeys(messages))
|
|
504
|
+
if any((err.extensions or {}).get("code") in ("FORBIDDEN", "AUTHENTICATION_ERROR") for err in errors):
|
|
505
|
+
text += " " + DENY_HINT
|
|
506
|
+
return text
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def build_tools(schema: GraphQLSchema, principal: Callable[[bool], dict]) -> list[Tool]:
|
|
510
|
+
"""principal(write) -> GraphQL context for the authenticated caller; raises ToolError."""
|
|
511
|
+
tools = []
|
|
512
|
+
specs = [(op, False, d) for op, d in READ_TOOLS.items()] + [(op, True, d) for op, d in WRITE_TOOLS.items()]
|
|
513
|
+
for op, write, description in specs:
|
|
514
|
+
spec = _Spec(schema, op, write, description)
|
|
515
|
+
tools.append(_make_tool(schema, spec, principal))
|
|
516
|
+
return tools
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _make_tool(schema: GraphQLSchema, spec: _Spec, principal: Callable[[bool], dict]) -> Tool:
|
|
520
|
+
async def run(args: dict) -> str:
|
|
521
|
+
context = principal(spec.write)
|
|
522
|
+
|
|
523
|
+
def internal(query: str, variables: dict | None) -> dict:
|
|
524
|
+
result = execute(schema, parse(query), variable_values=variables or {}, context_value=context)
|
|
525
|
+
return result.data or {}
|
|
526
|
+
|
|
527
|
+
flat = spec.assemble(args)
|
|
528
|
+
flat = _Resolver(internal, context["user_id"]).apply(spec.op, flat)
|
|
529
|
+
result = execute(schema, spec.document, variable_values=spec.variables(flat), context_value=context)
|
|
530
|
+
if result.errors:
|
|
531
|
+
raise ToolError(_error_text(spec.op, result.errors))
|
|
532
|
+
value = (result.data or {}).get(spec.op)
|
|
533
|
+
target = flat.get("id") or flat.get("issueId") or flat.get("teamId")
|
|
534
|
+
if value is None and spec.field.args:
|
|
535
|
+
subject = f" '{args.get('id', target)}'" if (args.get("id") or target) else ""
|
|
536
|
+
raise ToolError(f"hoja_{spec.op}: nothing found for{subject}. It may not exist or may not be visible to you.")
|
|
537
|
+
if value is False or (isinstance(value, dict) and value.get("success") is False):
|
|
538
|
+
subject = f" for '{args.get('id', target)}'" if (args.get("id") or target) else ""
|
|
539
|
+
raise ToolError(
|
|
540
|
+
f"hoja_{spec.op} did not apply{subject}: the target was not found or you are not allowed to change it. "
|
|
541
|
+
"Nothing was modified."
|
|
542
|
+
)
|
|
543
|
+
return json.dumps(result.data, ensure_ascii=False, default=str)
|
|
544
|
+
|
|
545
|
+
run.__name__ = "hoja_" + spec.op
|
|
546
|
+
destructive = spec.op in DESTRUCTIVE
|
|
547
|
+
annotations = ToolAnnotations(
|
|
548
|
+
title=spec.op,
|
|
549
|
+
read_only_hint=not spec.write,
|
|
550
|
+
destructive_hint=destructive if spec.write else None,
|
|
551
|
+
idempotent_hint=True if not spec.write or spec.op.endswith("Update") or spec.op.startswith(IDEMPOTENT_PREFIXES) else None,
|
|
552
|
+
open_world_hint=False,
|
|
553
|
+
)
|
|
554
|
+
return Tool(
|
|
555
|
+
fn=run,
|
|
556
|
+
name="hoja_" + spec.op,
|
|
557
|
+
description=spec.description + ("" if not spec.write else " Requires the hoja:write scope."),
|
|
558
|
+
parameters=spec.parameters,
|
|
559
|
+
fn_metadata=FuncMetadata(arg_model=_RawArgs),
|
|
560
|
+
is_async=True,
|
|
561
|
+
annotations=annotations,
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
INSTRUCTIONS = (
|
|
566
|
+
"Hoja is a Linear-compatible work tracker. Issues are referenced as TEAMKEY-N (e.g. ENG-12) and every "
|
|
567
|
+
"issue argument accepts that identifier. Start with hoja_viewer and hoja_teams to learn who you are and "
|
|
568
|
+
"which team keys exist; hoja_team(id: KEY) shows a team's workflow states and members. Reference fields "
|
|
569
|
+
"accept friendly values: teamId takes a team key; assigneeId/leadId/userId take 'me', an email or an exact "
|
|
570
|
+
"member name; stateId takes a state name like 'In Progress'; labelIds and projectId take names. For "
|
|
571
|
+
"multi-step work, create or reuse a parent issue and put actionable steps under it with parentId rather than "
|
|
572
|
+
"creating a stack of unrelated root issues; keep genuinely standalone issues flat. Results "
|
|
573
|
+
"contain the affected entity, so read them to confirm what changed. Errors name the argument that was "
|
|
574
|
+
"wrong; fix it instead of guessing other parameters. Omit optional arguments you do not need: empty "
|
|
575
|
+
"strings/lists and 0 for priority/estimate on updates are ignored (use priority \"none\" to clear it). "
|
|
576
|
+
"If a person, team or state does not exist, tell the "
|
|
577
|
+
"user rather than substituting another. Write tools require the hoja:write scope; confirm with the user "
|
|
578
|
+
"before deleting anything."
|
|
579
|
+
)
|