Coverage for rdgai/mcp_server.py: 98.39%

124 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1""" 

2An MCP server for classifying transitions between variant readings in a TEI critical apparatus. 

3 

4Run it with ``rdgai serve-mcp FILE`` (stdio) or ``rdgai serve-mcp FILE --transport http``. 

5""" 

6from contextlib import contextmanager 

7from typing import Annotated, Literal 

8 

9from pydantic import Field 

10from mcp.server.mcpserver import MCPServer 

11from mcp.server.mcpserver.exceptions import ToolError 

12from mcp_types import ToolAnnotations 

13 

14from .annotation import ( 

15 AnnotationError, 

16 AnnotationStore, 

17 CategoryCounts, 

18 RulesReport, 

19 DefinitionsChange, 

20 SampleFilter, 

21 SampleInfo, 

22 SimilarResults, 

23 SuggestionList, 

24 SuggestionResult, 

25 TranslationResult, 

26 UntranslatedList, 

27 CategoryPairList, 

28 Definitions, 

29 UnitList, 

30 UnitDetail, 

31 UnitStatus, 

32 WriteResult, 

33) 

34 

35INSTRUCTIONS = """\ 

36This server gives access to a TEI critical apparatus whose variant readings are being classified into 

37transcriptional change categories. 

38 

39Workflow: 

401. Call get_definitions first and follow its guidance (including any decision order) and direction convention. 

412. Use list_units to find units (e.g. status='unclassified', or by verse such as 'Mark.1.2'). 

423. Use get_unit to read a unit: its verse context, its readings and every pair of substantive readings. 

43 The only context is the verse given. 

444. Use set_classification to record a category for a pair. Its inverse is set automatically, so classify 

45 each unordered pair once. A new classification replaces the old one. 

46 

47Pairs formed by typed subreadings (e.g. orthographic readings 'ao', 'ao1' of reading 'a') are labelled 

48automatically by subreading rules (source 'rule'; see apply_rules) and are not counted as work: do not 

49classify them unless the annotator wants to override one. 

50 

51Do not suggest classifications for the sample's test units (they are refused unless the annotator explicitly asks): 

52suggestions there would leak into the evaluation. 

53 

54Annotating the sample: get_sample shows progress; list_units(sample='sampled', status='unclassified') 

55gives the next units in document order. Work through one unit at a time. 

56 

57The unit the annotator has open in the GUI is given by get_current_unit: use it when they say "this verse" or 

58"the verse I'm on". 

59 

60Translations: the annotator sees, for each pair, an English translation of the whole verse with each reading in 

61place. list_untranslated gives the units still to translate (e.g. sample='sampled'); get_unit shows the verse 

62(context_before, the reading, context_after) and any translations made so far. For each substantive reading, translate 

63the whole verse with that reading in place and save them with set_translations. Translate closely enough that the 

64difference between the readings shows, and word the rest of the verse identically in every translation so that only 

65the differences stand out. Mark the words that render the reading with ⸂…⸃ (several spans if the English word order 

66splits them), and put ⸆ where an omitted reading's words would have been, e.g. 'of Jesus ⸂Christ⸃, Son of God' and 

67'of Jesus⸆, Son of God'. Translations are not classifications: do not suggest categories in them. 

68 

69When working with a human annotator, propose a category with a brief reason for each pair of the unit, 

70and only call set_classification for the labels the annotator has agreed to, with the certainty they 

71choose (high, medium or low). Record the annotator's reasoning as the justification. 

72""" 

73 

74 

75@contextmanager 

76def tool_errors(): 

77 """ Reports expected errors (unknown unit, reading or category, read-only, ...) to the client. """ 

78 try: 

79 yield 

80 except AnnotationError as error: 

81 raise ToolError(str(error)) from error 

82 

83 

84def build_server(store:AnnotationStore) -> MCPServer: 

85 server = MCPServer(name="rdgai", instructions=INSTRUCTIONS) 

86 read_only = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False) 

87 write = ToolAnnotations(readOnlyHint=False, destructiveHint=True, idempotentHint=True, openWorldHint=False) 

88 

89 @server.tool(annotations=read_only) 

90 def get_definitions() -> Definitions: 

91 """ 

92 Returns the transcriptional change categories with their definitions and inverses, the guidance 

93 given with them (e.g. the decision order) and the direction convention for active/passive readings. 

94 """ 

95 with tool_errors(): 

96 return store.definitions() 

97 

98 @server.tool(annotations=read_only) 

99 def list_units( 

100 status: Annotated[UnitStatus, Field(description="Filter by classification status of the unit's pairs.")] = "all", 

101 verse: Annotated[str, Field(description="Only units in this verse or chapter, e.g. 'Mark.1.2' or 'Mark.1'.")] = "", 

102 sample: Annotated[SampleFilter, Field(description="Only units in the sample ('sampled'), in its example or test set, or not in the sample.")] = "all", 

103 offset: Annotated[int, Field(ge=0)] = 0, 

104 limit: Annotated[int, Field(ge=1, le=500)] = 50, 

105 ) -> UnitList: 

106 """ 

107 Lists variation units with their number of readings, pairs to classify and pairs classified. 

108 Units with no substantive pairs have status 'nothing_to_classify'. 

109 """ 

110 with tool_errors(): 

111 return store.list_units(status=status, verse=verse, sample=sample, offset=offset, limit=limit) 

112 

113 @server.tool(annotations=read_only) 

114 def get_unit( 

115 unit_id: Annotated[str, Field(description="The variation unit's id, e.g. 'Mark.1.1.12-16'.")], 

116 pair_order: Annotated[Literal["document", "attestation"], Field( 

117 description="'document': pairs in document order of their readings. 'attestation': each pair oriented " 

118 "with the better-attested reading first, as the annotation GUI shows them." 

119 )] = "document", 

120 ) -> UnitDetail: 

121 """ 

122 Returns a variation unit: the verse with the unit marked ⸂…⸃, the readings (OMIT is an omission; 

123 editorial notes found in a reading's text are listed separately and are not part of the reading), 

124 lacunose witnesses, and each unordered pair of substantive readings with its current category 

125 and provenance (who classified it, when, certainty, justification and definitions version). 

126 """ 

127 with tool_errors(): 

128 return store.get_unit(unit_id, pair_order=pair_order) 

129 

130 @server.tool(annotations=read_only) 

131 def category_counts() -> CategoryCounts: 

132 """ 

133 Returns how many pairs have each category (counting each direction separately), split into 

134 human (certain) and pipeline (tentative) classifications, and how many pairs are classified overall. 

135 """ 

136 with tool_errors(): 

137 return store.category_counts() 

138 

139 @server.tool(annotations=read_only) 

140 def list_category( 

141 category: Annotated[str, Field(description="The category name.")], 

142 source: Annotated[Literal["all", "human", "pipeline"], Field(description="Only pairs classified by a human or by the pipeline.")] = "all", 

143 offset: Annotated[int, Field(ge=0)] = 0, 

144 limit: Annotated[int, Field(ge=1, le=500)] = 50, 

145 ) -> CategoryPairList: 

146 """ 

147 Lists the pairs classified with a category (in the direction active → passive), with their verse 

148 context and provenance. Useful for checking consistency and finding precedents. 

149 """ 

150 with tool_errors(): 

151 return store.list_category(category, source=source, offset=offset, limit=limit) 

152 

153 @server.tool(annotations=read_only) 

154 def get_sample() -> SampleInfo: 

155 """ 

156 Returns the random sample of units (if one has been drawn): its seed and settings, each sampled 

157 unit with its role (example or test) and status, and progress overall and by role. 

158 To annotate the sample in order, use list_units with sample='sampled' and status='unclassified'. 

159 """ 

160 with tool_errors(): 

161 return store.sample_info() 

162 

163 @server.tool(annotations=read_only) 

164 def get_suggestions( 

165 unit_id: Annotated[str | None, Field(description="Only suggestions for this unit.")] = None, 

166 active: Annotated[str | None, Field(description="With passive: only suggestions for this pair, in this direction.")] = None, 

167 passive: Annotated[str | None, Field(description="With active: only suggestions for this pair, in this direction.")] = None, 

168 source: Annotated[str | None, Field(description="Only suggestions from this source, e.g. 'claude' or 'rdgai:<model>'.")] = None, 

169 ) -> SuggestionList: 

170 """ 

171 Returns suggested classifications (kept separately from labels; they are not classifications). 

172 Without a pair, each suggestion is given once, for the pair in document order. 

173 """ 

174 with tool_errors(): 

175 return SuggestionList(suggestions=store.get_suggestions(unit_id, active, passive, source)) 

176 

177 @server.tool(annotations=read_only) 

178 def search_similar( 

179 unit_id: Annotated[str, Field(description="The variation unit's id.")], 

180 active: Annotated[str, Field(description="Id of the active (first) reading.")], 

181 passive: Annotated[str, Field(description="Id of the passive (second) reading.")], 

182 limit: Annotated[int, Field(ge=1, le=50)] = 10, 

183 include_pipeline: Annotated[bool, Field(description="Also return pipeline labels (tentative; weigh them much less than human labels).")] = True, 

184 categories: Annotated[list[str] | None, Field(description="Only pairs labelled with one of these categories (e.g. to find the closest contrasting precedent).")] = None, 

185 ) -> SimilarResults: 

186 """ 

187 Finds labelled pairs whose change resembles this pair's (what the second reading adds or omits, and the 

188 words around the unit), best first, with their category, who labelled them and why. Use them as precedents: 

189 human labels are certain, pipeline labels are tentative. The pair itself and its inverse are never returned. 

190 """ 

191 with tool_errors(): 

192 results = store.search_similar( 

193 unit_id, active, passive, limit=limit, sources=("human", "pipeline") if include_pipeline else ("human",), 

194 categories=categories, 

195 ) 

196 app = store.get_app(unit_id) 

197 pair = store.get_pair(app, active, passive) 

198 from .diff import describe_change 

199 query = dict(unit_id=unit_id, active=active, passive=passive, change=describe_change(pair.active.text, pair.passive.text).text) 

200 return SimilarResults(query=query, results=results) 

201 

202 if not store.read_only and not store.lock_definitions: 

203 @server.tool(annotations=write) 

204 def update_category( 

205 name: Annotated[str, Field(description="The category to change.")], 

206 description: Annotated[str | None, Field(description="The new definition text (omit to keep it).")] = None, 

207 new_name: Annotated[str | None, Field(description="A new name (omit to keep it). Classifications using the category are updated.")] = None, 

208 ) -> DefinitionsChange: 

209 """ 

210 Changes a category's definition and/or renames it. Renaming also updates its inverse's link and 

211 every classification that uses it. Only make changes the annotator has asked for. 

212 """ 

213 with tool_errors(): 

214 return store.update_category(name, description=description, new_name=new_name) 

215 

216 @server.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)) 

217 def add_category( 

218 name: Annotated[str, Field(description="Name of the new category (a valid xml:id, e.g. 'Harmonization').")], 

219 description: Annotated[str, Field(description="The definition of the new category.")], 

220 inverse_name: Annotated[str | None, Field(description="For a reciprocal pair (like Addition/Omission), the name of the new inverse category.")] = None, 

221 inverse_description: Annotated[str, Field(description="The definition of the inverse category.")] = "", 

222 ) -> DefinitionsChange: 

223 """ 

224 Adds a category. Without inverse_name it is its own inverse (like Transposition); with inverse_name 

225 a reciprocal pair is added. Only make changes the annotator has asked for. 

226 """ 

227 with tool_errors(): 

228 return store.add_category(name, description, inverse_name=inverse_name, inverse_description=inverse_description) 

229 

230 @server.tool(annotations=write) 

231 def remove_category( 

232 name: Annotated[str, Field(description="The category to remove (its inverse is removed too).")], 

233 reassign_to: Annotated[str | None, Field(description="Category to move existing classifications to; required if the category is in use.")] = None, 

234 ) -> DefinitionsChange: 

235 """ 

236 Removes a category and its inverse. If pairs are classified with them, reassign_to must give a 

237 category with a matching inverse structure; their labels move to it with their provenance kept. 

238 Only make changes the annotator has asked for. 

239 """ 

240 with tool_errors(): 

241 return store.remove_category(name, reassign_to=reassign_to) 

242 

243 @server.tool(annotations=write) 

244 def update_guidance( 

245 guidance: Annotated[str, Field(description="The full new guidance text (e.g. the decision order). Replaces the old guidance.")], 

246 ) -> DefinitionsChange: 

247 """ 

248 Replaces the guidance kept in the XML comment before the category definitions (e.g. the decision 

249 order). Read the current guidance with get_definitions first. Only make changes the annotator has asked for. 

250 """ 

251 with tool_errors(): 

252 return store.update_guidance(guidance) 

253 

254 @server.tool(annotations=write) 

255 def update_classifier_instructions( 

256 instructions: Annotated[str, Field(description="The full new classifier instructions for this file (empty to remove them). Replaces the old text.")], 

257 ) -> DefinitionsChange: 

258 """ 

259 Replaces this file's instructions for the classification pipeline (kept in the TEI next to the definitions; 

260 shown with get_definitions). Only make changes the annotator has asked for. 

261 """ 

262 with tool_errors(): 

263 return store.update_classifier_instructions(instructions) 

264 

265 @server.tool(annotations=write) 

266 def set_category_constraints( 

267 category: Annotated[str, Field(description="The category.")], 

268 constraints: Annotated[list[str], Field(description="Constraint names (adds-only, omits-only, keeps-word-count, not-only-adds-or-omits; or rules-only for a category only the subreading rules assign); empty to remove.")], 

269 ) -> DefinitionsChange: 

270 """ 

271 Sets the constraints a category declares on the computed change between two readings; the pipeline asks the 

272 model to reconsider a decision whose change breaks them. Only make changes the annotator has asked for. 

273 """ 

274 with tool_errors(): 

275 return store.set_category_constraints(category, constraints) 

276 

277 if not store.read_only and not store.evaluation: 

278 # not in evaluation mode: a new sample would change the test units, and rules would change their labels 

279 @server.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=True, idempotentHint=True, openWorldHint=False)) 

280 def draw_sample( 

281 size: Annotated[int, Field(ge=1, description="Number of units to sample.")], 

282 seed: Annotated[int, Field(description="Random seed; the same seed and settings give the same sample.")], 

283 test_fraction: Annotated[float, Field(ge=0.0, le=1.0, description="Fraction of the sampled units held out as test units.")] = 0.5, 

284 max_pairs: Annotated[int | None, Field(ge=1, description="Exclude units with more pairs than this from the sample.")] = None, 

285 overwrite: Annotated[bool, Field(description="Replace an existing sample. Only do this if the user explicitly asks.")] = False, 

286 ) -> SampleInfo: 

287 """ 

288 Draws a reproducible random sample of variation units (those with at least one pair to classify) 

289 and splits it into example and test units. The sample is saved in a sidecar YAML file. 

290 Refuses to replace an existing sample unless overwrite is true. 

291 """ 

292 with tool_errors(): 

293 return store.draw_sample(size=size, seed=seed, test_fraction=test_fraction, max_pairs=max_pairs, overwrite=overwrite) 

294 

295 @server.tool(annotations=write) 

296 def apply_rules( 

297 rules: Annotated[dict[str, str] | None, Field(description="Reading type -> category, e.g. {'orthographic': 'Orthography'}. Replaces the rules stored in the file. Omit to use the stored rules.")] = None, 

298 suffixes: Annotated[dict[str, str] | None, Field(description="Reading type -> id suffix, e.g. {'orthographic': 'o'} ('ao2' is a subreading of 'a'). Defaults: orthographic 'o', defective 'f'.")] = None, 

299 dry_run: Annotated[bool, Field(description="Report what would change without saving.")] = False, 

300 ) -> RulesReport: 

301 """ 

302 Labels the pairs formed by typed subreadings (e.g. orthographic readings 'ao', 'ao1' of reading 'a'): 

303 a subreading and its parent, and two subreadings of the same parent, get the mapped category. Any other 

304 pair with a subreading (e.g. ao-b) is an ordinary pair to classify; rule labels left on such pairs (from the 

305 former rule 3) are removed. Human labels are never changed; those that disagree are reported as conflicts. 

306 """ 

307 from .rules import build_rules 

308 with tool_errors(): 

309 try: 

310 rule_list = build_rules(store.rules, rules, suffixes) 

311 except ValueError as error: 

312 raise AnnotationError(str(error)) 

313 return store.apply_rules(rule_list, dry_run=dry_run) 

314 

315 @server.tool(annotations=read_only) 

316 def get_current_unit() -> UnitDetail: 

317 """ 

318 The unit the annotator has open in the annotation GUI, in full (as get_unit). Use it when the annotator 

319 refers to "this verse", "this unit" or "the verse I'm on", e.g. to translate it with set_translations. 

320 """ 

321 with tool_errors(): 

322 viewing = store.viewing() 

323 if viewing is None: 

324 raise AnnotationError("No unit is open in the annotation GUI. Ask the annotator which unit they mean.") 

325 return store.get_unit(viewing.unit_id, pair_order="attestation") 

326 

327 @server.tool(annotations=read_only) 

328 def list_untranslated( 

329 sample: Annotated[SampleFilter, Field(description="Which units: 'sampled', 'example', 'test', 'unsampled' or 'all'.")] = "sampled", 

330 verse: Annotated[str, Field(description="Only units in this verse or chapter, e.g. 'Mark.1.2'.")] = "", 

331 limit: Annotated[int, Field(description="Maximum number of unit ids to return.")] = 50, 

332 ) -> UntranslatedList: 

333 """ Lists the units (in document order) with a substantive reading that has no contextual translation yet. """ 

334 with tool_errors(): 

335 unit_ids = store.untranslated_units(sample=sample, verse=verse) 

336 return UntranslatedList(total=len(unit_ids), unit_ids=unit_ids[:max(limit, 1)]) 

337 

338 if not store.read_only: 

339 @server.tool(annotations=write) 

340 def set_translations( 

341 unit_id: Annotated[str, Field(description="The variation unit's id.")], 

342 translations: Annotated[dict[str, str], Field(description="{reading id: English translation of the whole verse with that reading in place}, with the words that render the reading marked ⸂…⸃ and ⸆ where an omitted reading would be, e.g. 'of Jesus ⸂Christ⸃, Son of God' / 'of Jesus⸆, Son of God'.")], 

343 source: Annotated[str, Field(description="Who translated: 'claude' by default.")] = "claude", 

344 ) -> TranslationResult: 

345 """ 

346 Saves contextual translations for a unit's readings: for each reading, the whole verse translated with that 

347 reading in place. They are shown to the annotator beside each pair and stored in a sidecar file (never in the 

348 TEI). Existing translations of other readings are kept; the result lists the readings still missing. 

349 """ 

350 with tool_errors(): 

351 return store.set_translations(unit_id, translations, source=source) 

352 

353 @server.tool(annotations=write) 

354 def suggest_classification( 

355 unit_id: Annotated[str, Field(description="The variation unit's id.")], 

356 active: Annotated[str, Field(description="Id of the active (first) reading.")], 

357 passive: Annotated[str, Field(description="Id of the passive (second) reading.")], 

358 category: Annotated[str, Field(description="Suggested category for the change from the active to the passive reading.")], 

359 justification: Annotated[str, Field(description="A short reason for the suggestion.")] = "", 

360 source: Annotated[str, Field(description="Who is suggesting: 'claude', or e.g. 'rdgai:<model>'.")] = "claude", 

361 allow_test_unit: Annotated[bool, Field(description="Suggestions on the sample's test units are refused, because they would leak into the evaluation. Set only if the annotator explicitly asks.")] = False, 

362 ) -> SuggestionResult: 

363 """ 

364 Records a suggested category for a pair without classifying it. Suggestions are shown to the 

365 annotator in the GUI (in bold, with the justification) and are stored separately from labels, 

366 so they never affect the phylogenetic analysis. A new suggestion from the same source replaces 

367 the previous one for the pair. Use this to propose labels for the annotator to review. 

368 """ 

369 with tool_errors(): 

370 return store.suggest_classification( 

371 unit_id, active, passive, category, justification=justification, source=source, allow_test_unit=allow_test_unit, 

372 ) 

373 

374 @server.tool(annotations=write) 

375 def set_classification( 

376 unit_id: Annotated[str, Field(description="The variation unit's id.")], 

377 active: Annotated[str, Field(description="Id of the active (first) reading.")], 

378 passive: Annotated[str, Field(description="Id of the passive (second) reading.")], 

379 category: Annotated[str, Field(description="Category for the change from the active to the passive reading.")], 

380 justification: Annotated[str, Field(description="A short reason for the decision.")] = "", 

381 cert: Annotated[Literal["high", "medium", "low"], Field(description="The annotator's certainty.")] = "high", 

382 ) -> WriteResult: 

383 """ 

384 Sets the category for the change from the active reading to the passive reading, replacing any 

385 existing category. The inverse category is set on the reverse pair, and the file is saved. 

386 Recorded as the human annotator's decision. 

387 """ 

388 with tool_errors(): 

389 return store.set_classification(unit_id, active, passive, category, justification=justification, cert=cert) 

390 

391 @server.tool(annotations=write) 

392 def clear_classification( 

393 unit_id: Annotated[str, Field(description="The variation unit's id.")], 

394 active: Annotated[str, Field(description="Id of the active (first) reading.")], 

395 passive: Annotated[str, Field(description="Id of the passive (second) reading.")], 

396 ) -> WriteResult: 

397 """ Removes the classification of a pair and of its reverse pair, and saves the file. """ 

398 with tool_errors(): 

399 return store.clear_classification(unit_id, active, passive) 

400 

401 return server