package mcp-kit

All checked builds pass
  1. Overview
  2. Docs
OCaml library for building MCP servers

Install

dune-project
 Dependency

Authors

Maintainers

Sources

ocaml-mcp-v0.2.0.tar.gz
sha256=43c8319a13be91e323ae952a71ab673533fb3295886029eed9d81e5828de5ef7

doc/src/mcp-kit.jsonschema-core/registry.ml.html

Source file registry.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
(** Schema registry — stores and resolves schemas by URI. *)

type validator = Yojson.Safe.t -> Json_pointer.t -> Error.t list
type retriever = Uri.t -> Yojson.Safe.t option

type schema_dialect = {
  id_keyword : string;
  anchor_keyword : string option;
  dynamic_anchor_keyword : string option;
  schema_keywords : string list;
  schema_map_keywords : string list;
  schema_array_keywords : string list;
  schema_or_array_keywords : string list;
  schema_or_dep_keywords : string list;
}

type schema_dialect_selector = schema_dialect -> Yojson.Safe.t -> schema_dialect

type schema_resource = {
  path : Json_pointer.t;
  schema_uri : string;
  schema : Yojson.Safe.t;
}

type compile_state =
  | Compiling of (validator -> unit) list ref
  | Compiled of validator

type t = {
  raw : (string, Yojson.Safe.t) Hashtbl.t;
  base_context : (string, Uri.t) Hashtbl.t;
  path_context : (string, Json_pointer.t) Hashtbl.t;
  dynamic_anchors : (string, (string * Uri.t) list) Hashtbl.t;
  dynamic_anchor_uris : (string, unit) Hashtbl.t;
  state : (string, compile_state) Hashtbl.t;
  schema_dialect : schema_dialect;
  schema_dialect_selector : schema_dialect_selector;
  retriever : retriever option;
}

let uri_key uri = Uri.to_string (Uri_util.without_fragment uri)

let draft03_schema_dialect =
  {
    id_keyword = "id";
    anchor_keyword = None;
    dynamic_anchor_keyword = None;
    schema_keywords = [ "additionalItems"; "additionalProperties" ];
    schema_map_keywords = [ "properties"; "patternProperties"; "definitions" ];
    schema_array_keywords = [];
    schema_or_array_keywords = [ "items"; "extends" ];
    schema_or_dep_keywords = [ "dependencies" ];
  }

let draft04_schema_dialect =
  {
    id_keyword = "id";
    anchor_keyword = None;
    dynamic_anchor_keyword = None;
    schema_keywords = [ "additionalItems"; "additionalProperties"; "not" ];
    schema_map_keywords = [ "properties"; "patternProperties"; "definitions" ];
    schema_array_keywords = [ "allOf"; "anyOf"; "oneOf" ];
    schema_or_array_keywords = [ "items" ];
    schema_or_dep_keywords = [ "dependencies" ];
  }

let draft06_schema_dialect =
  {
    id_keyword = "$id";
    anchor_keyword = None;
    dynamic_anchor_keyword = None;
    schema_keywords =
      [
        "additionalItems";
        "additionalProperties";
        "contains";
        "not";
        "propertyNames";
      ];
    schema_map_keywords = [ "properties"; "patternProperties"; "definitions" ];
    schema_array_keywords = [ "allOf"; "anyOf"; "oneOf" ];
    schema_or_array_keywords = [ "items" ];
    schema_or_dep_keywords = [ "dependencies" ];
  }

let draft07_schema_dialect =
  {
    draft06_schema_dialect with
    schema_keywords =
      [
        "additionalItems";
        "additionalProperties";
        "contains";
        "if";
        "then";
        "else";
        "not";
        "propertyNames";
      ];
  }

let draft2019_09_schema_dialect =
  {
    id_keyword = "$id";
    anchor_keyword = Some "$anchor";
    dynamic_anchor_keyword = None;
    schema_keywords =
      [
        "additionalItems";
        "additionalProperties";
        "contains";
        "if";
        "then";
        "else";
        "not";
        "propertyNames";
        "unevaluatedItems";
        "unevaluatedProperties";
      ];
    schema_map_keywords = [ "properties"; "patternProperties"; "$defs" ];
    schema_array_keywords = [ "allOf"; "anyOf"; "oneOf" ];
    schema_or_array_keywords = [ "items" ];
    schema_or_dep_keywords = [ "dependencies"; "dependentSchemas" ];
  }

let draft2020_12_schema_dialect =
  {
    id_keyword = "$id";
    anchor_keyword = Some "$anchor";
    dynamic_anchor_keyword = Some "$dynamicAnchor";
    schema_keywords =
      [
        "additionalProperties";
        "contains";
        "if";
        "then";
        "else";
        "items";
        "not";
        "propertyNames";
        "unevaluatedItems";
        "unevaluatedProperties";
      ];
    schema_map_keywords = [ "properties"; "patternProperties"; "$defs" ];
    schema_array_keywords = [ "allOf"; "anyOf"; "oneOf"; "prefixItems" ];
    schema_or_array_keywords = [];
    schema_or_dep_keywords = [ "dependentSchemas" ];
  }

let strip_trailing_hash s =
  let len = String.length s in
  if len > 0 && s.[len - 1] = '#' then String.sub s 0 (len - 1) else s

let schema_uri = function
  | `Assoc pairs -> (
      match List.assoc_opt "$schema" pairs with
      | Some (`String uri) -> Some (strip_trailing_hash uri)
      | _ -> None)
  | _ -> None

let standard_schema_dialect_selector current schema_json =
  match schema_uri schema_json with
  | Some
      ( "http://json-schema.org/draft-03/schema"
      | "https://json-schema.org/draft-03/schema" ) ->
      draft03_schema_dialect
  | Some
      ( "http://json-schema.org/draft-04/schema"
      | "https://json-schema.org/draft-04/schema" ) ->
      draft04_schema_dialect
  | Some
      ( "http://json-schema.org/draft-06/schema"
      | "https://json-schema.org/draft-06/schema" ) ->
      draft06_schema_dialect
  | Some
      ( "http://json-schema.org/draft-07/schema"
      | "https://json-schema.org/draft-07/schema" ) ->
      draft07_schema_dialect
  | Some
      ( "http://json-schema.org/draft/2019-09/schema"
      | "https://json-schema.org/draft/2019-09/schema" ) ->
      draft2019_09_schema_dialect
  | Some
      ( "http://json-schema.org/draft/2020-12/schema"
      | "https://json-schema.org/draft/2020-12/schema" ) ->
      draft2020_12_schema_dialect
  | _ -> current

let create ?(schema_dialect = draft07_schema_dialect)
    ?(schema_dialect_selector = fun current _ -> current) ?retriever () =
  {
    raw = Hashtbl.create 64;
    base_context = Hashtbl.create 64;
    path_context = Hashtbl.create 64;
    dynamic_anchors = Hashtbl.create 64;
    dynamic_anchor_uris = Hashtbl.create 64;
    state = Hashtbl.create 64;
    schema_dialect;
    schema_dialect_selector;
    retriever;
  }

let register_dynamic_anchor t ~resource_uri name anchor_uri =
  let resource_key = uri_key resource_uri in
  let anchors =
    Hashtbl.find_opt t.dynamic_anchors resource_key
    |> Option.value ~default:[]
    |> List.filter (fun (existing, _) -> existing <> name)
  in
  Hashtbl.replace t.dynamic_anchors resource_key
    (anchors @ [ (name, anchor_uri) ]);
  Hashtbl.replace t.dynamic_anchor_uris (Uri.to_string anchor_uri) ()

let has_string_member name pairs =
  match List.assoc_opt name pairs with Some (`String _) -> true | _ -> false

let error_at path keyword message =
  Error.make ~instance_path:path ~schema_path:path ~keyword message

let uri_of_string_opt s = try Some (Uri.of_string s) with _ -> None

let schema_uri_keyword_errors path value =
  let keyword_path = Json_pointer.append path "$schema" in
  match value with
  | `String uri_str -> (
      match uri_of_string_opt uri_str with
      | None -> [ error_at keyword_path "$schema" "$schema must be a URI" ]
      | Some uri ->
          let scheme_error =
            match Uri.scheme uri with
            | Some scheme when scheme <> "" -> []
            | _ ->
                [
                  error_at keyword_path "$schema"
                    "$schema URI must contain a scheme";
                ]
          in
          let normalized = Uri.to_string (Uri_util.normalize uri) in
          let normalization_error =
            if normalized = uri_str then []
            else
              [
                error_at keyword_path "$schema" "$schema URI must be normalized";
              ]
          in
          scheme_error @ normalization_error)
  | _ -> [ error_at keyword_path "$schema" "$schema must be a URI string" ]

let rec collect_schema_keyword_errors ~schema_dialect ~schema_dialect_selector
    ~path (json : Yojson.Safe.t) =
  match json with
  | `Assoc pairs ->
      let selected_dialect = schema_dialect_selector schema_dialect json in
      let is_resource_boundary =
        path = Json_pointer.empty
        || has_string_member schema_dialect.id_keyword pairs
        || has_string_member selected_dialect.id_keyword pairs
      in
      let schema_dialect =
        if is_resource_boundary then selected_dialect else schema_dialect
      in
      let own_errors =
        match List.assoc_opt "$schema" pairs with
        | Some value ->
            let placement_errors =
              if is_resource_boundary then []
              else
                [
                  error_at
                    (Json_pointer.append path "$schema")
                    "$schema" "$schema must not appear in an ordinary subschema";
                ]
            in
            placement_errors @ schema_uri_keyword_errors path value
        | None -> []
      in
      let child_errors =
        List.concat_map
          (fun (k, v) ->
            let keyword_path = Json_pointer.append path k in
            if List.mem k schema_dialect.schema_keywords then
              collect_schema_keyword_errors ~schema_dialect
                ~schema_dialect_selector ~path:keyword_path v
            else if List.mem k schema_dialect.schema_map_keywords then
              match v with
              | `Assoc props ->
                  List.concat_map
                    (fun (name, sv) ->
                      collect_schema_keyword_errors ~schema_dialect
                        ~schema_dialect_selector
                        ~path:(Json_pointer.append keyword_path name)
                        sv)
                    props
              | _ -> []
            else if List.mem k schema_dialect.schema_array_keywords then
              match v with
              | `List items ->
                  List.mapi
                    (fun index sv ->
                      collect_schema_keyword_errors ~schema_dialect
                        ~schema_dialect_selector
                        ~path:
                          (Json_pointer.append keyword_path
                             (string_of_int index))
                        sv)
                    items
                  |> List.concat
              | _ -> []
            else if List.mem k schema_dialect.schema_or_array_keywords then
              match v with
              | `List items ->
                  List.mapi
                    (fun index sv ->
                      collect_schema_keyword_errors ~schema_dialect
                        ~schema_dialect_selector
                        ~path:
                          (Json_pointer.append keyword_path
                             (string_of_int index))
                        sv)
                    items
                  |> List.concat
              | _ ->
                  collect_schema_keyword_errors ~schema_dialect
                    ~schema_dialect_selector ~path:keyword_path v
            else if List.mem k schema_dialect.schema_or_dep_keywords then
              match v with
              | `Assoc deps ->
                  List.concat_map
                    (fun (name, dv) ->
                      match dv with
                      | `Assoc _ | `Bool _ ->
                          collect_schema_keyword_errors ~schema_dialect
                            ~schema_dialect_selector
                            ~path:(Json_pointer.append keyword_path name)
                            dv
                      | _ -> [])
                    deps
              | _ -> []
            else [])
          pairs
      in
      own_errors @ child_errors
  | _ -> []

let validate_schema_keywords ~schema_dialect ~schema_dialect_selector schema =
  collect_schema_keyword_errors ~schema_dialect ~schema_dialect_selector
    ~path:Json_pointer.empty schema

let rec collect_schema_resources_with_schema_uri ~schema_dialect
    ~schema_dialect_selector ~path (json : Yojson.Safe.t) =
  match json with
  | `Assoc pairs ->
      let selected_dialect = schema_dialect_selector schema_dialect json in
      let is_resource_boundary =
        path = Json_pointer.empty
        || has_string_member schema_dialect.id_keyword pairs
        || has_string_member selected_dialect.id_keyword pairs
      in
      let schema_dialect =
        if is_resource_boundary then selected_dialect else schema_dialect
      in
      let own_resource =
        match (is_resource_boundary, List.assoc_opt "$schema" pairs) with
        | true, Some (`String schema_uri) ->
            [ { path; schema_uri; schema = json } ]
        | _ -> []
      in
      let child_resources =
        List.concat_map
          (fun (k, v) ->
            let keyword_path = Json_pointer.append path k in
            if List.mem k schema_dialect.schema_keywords then
              collect_schema_resources_with_schema_uri ~schema_dialect
                ~schema_dialect_selector ~path:keyword_path v
            else if List.mem k schema_dialect.schema_map_keywords then
              match v with
              | `Assoc props ->
                  List.concat_map
                    (fun (name, sv) ->
                      collect_schema_resources_with_schema_uri ~schema_dialect
                        ~schema_dialect_selector
                        ~path:(Json_pointer.append keyword_path name)
                        sv)
                    props
              | _ -> []
            else if List.mem k schema_dialect.schema_array_keywords then
              match v with
              | `List items ->
                  List.mapi
                    (fun index sv ->
                      collect_schema_resources_with_schema_uri ~schema_dialect
                        ~schema_dialect_selector
                        ~path:
                          (Json_pointer.append keyword_path
                             (string_of_int index))
                        sv)
                    items
                  |> List.concat
              | _ -> []
            else if List.mem k schema_dialect.schema_or_array_keywords then
              match v with
              | `List items ->
                  List.mapi
                    (fun index sv ->
                      collect_schema_resources_with_schema_uri ~schema_dialect
                        ~schema_dialect_selector
                        ~path:
                          (Json_pointer.append keyword_path
                             (string_of_int index))
                        sv)
                    items
                  |> List.concat
              | _ ->
                  collect_schema_resources_with_schema_uri ~schema_dialect
                    ~schema_dialect_selector ~path:keyword_path v
            else if List.mem k schema_dialect.schema_or_dep_keywords then
              match v with
              | `Assoc deps ->
                  List.concat_map
                    (fun (name, dv) ->
                      match dv with
                      | `Assoc _ | `Bool _ ->
                          collect_schema_resources_with_schema_uri
                            ~schema_dialect ~schema_dialect_selector
                            ~path:(Json_pointer.append keyword_path name)
                            dv
                      | _ -> [])
                    deps
              | _ -> []
            else [])
          pairs
      in
      own_resource @ child_resources
  | _ -> []

let schema_resources_with_schema_uri ~schema_dialect ~schema_dialect_selector
    schema =
  collect_schema_resources_with_schema_uri ~schema_dialect
    ~schema_dialect_selector ~path:Json_pointer.empty schema

(** Recursively scan a schema for dialect-specific id keywords and register
    sub-schemas. Only traverses keyword values that are schemas for the active
    dialect. *)
let rec index_ids t ~schema_dialect ~base_uri ~path (json : Yojson.Safe.t) =
  match json with
  | `Assoc pairs ->
      let selected_dialect = t.schema_dialect_selector schema_dialect json in
      let schema_dialect =
        if
          path = Json_pointer.empty
          || has_string_member schema_dialect.id_keyword pairs
          || has_string_member selected_dialect.id_keyword pairs
        then selected_dialect
        else schema_dialect
      in
      let new_base =
        match List.assoc_opt schema_dialect.id_keyword pairs with
        | Some (`String id_str) ->
            let id_uri = Uri.of_string id_str in
            let resolved = Uri_util.resolve ~base:base_uri id_uri in
            let key = Uri.to_string resolved in
            Hashtbl.replace t.raw key json;
            Hashtbl.replace t.base_context key base_uri;
            Hashtbl.replace t.path_context key path;
            if Uri_util.fragment id_uri <> None && Uri.path id_uri = "" then
              base_uri
            else Uri_util.without_fragment resolved
        | _ -> base_uri
      in
      let register_anchor anchor_keyword =
        match List.assoc_opt anchor_keyword pairs with
        | Some (`String anchor) ->
            let anchor_uri = Uri.with_fragment new_base (Some anchor) in
            let key = Uri.to_string anchor_uri in
            let base_context =
              match List.assoc_opt schema_dialect.id_keyword pairs with
              | Some (`String _) -> base_uri
              | _ -> new_base
            in
            Hashtbl.replace t.raw key json;
            Hashtbl.replace t.base_context key base_context;
            Hashtbl.replace t.path_context key path
        | _ -> ()
      in
      (match schema_dialect.anchor_keyword with
      | Some anchor_keyword -> register_anchor anchor_keyword
      | None -> ());
      (match schema_dialect.dynamic_anchor_keyword with
      | Some anchor_keyword -> (
          register_anchor anchor_keyword;
          match List.assoc_opt anchor_keyword pairs with
          | Some (`String anchor) ->
              let anchor_uri = Uri.with_fragment new_base (Some anchor) in
              register_dynamic_anchor t ~resource_uri:new_base anchor anchor_uri
          | _ -> ())
      | None -> ());
      List.iter
        (fun (k, v) ->
          let keyword_path = Json_pointer.append path k in
          if List.mem k schema_dialect.schema_keywords then
            index_ids t ~schema_dialect ~base_uri:new_base ~path:keyword_path v
          else if List.mem k schema_dialect.schema_map_keywords then
            match v with
            | `Assoc props ->
                List.iter
                  (fun (name, sv) ->
                    index_ids t ~schema_dialect ~base_uri:new_base
                      ~path:(Json_pointer.append keyword_path name)
                      sv)
                  props
            | _ -> ()
          else if List.mem k schema_dialect.schema_array_keywords then
            match v with
            | `List items ->
                List.iteri
                  (fun index sv ->
                    index_ids t ~schema_dialect ~base_uri:new_base
                      ~path:
                        (Json_pointer.append keyword_path (string_of_int index))
                      sv)
                  items
            | _ -> ()
          else if List.mem k schema_dialect.schema_or_array_keywords then
            match v with
            | `List items ->
                List.iteri
                  (fun index sv ->
                    index_ids t ~schema_dialect ~base_uri:new_base
                      ~path:
                        (Json_pointer.append keyword_path (string_of_int index))
                      sv)
                  items
            | _ ->
                index_ids t ~schema_dialect ~base_uri:new_base
                  ~path:keyword_path v
          else if List.mem k schema_dialect.schema_or_dep_keywords then
            match v with
            | `Assoc deps ->
                List.iter
                  (fun (name, dv) ->
                    match dv with
                    | `Assoc _ | `Bool _ ->
                        index_ids t ~schema_dialect ~base_uri:new_base
                          ~path:(Json_pointer.append keyword_path name)
                          dv
                    | _ -> ())
                  deps
            | _ -> ()
          else if k = "$ref" then ()
          else ())
        pairs
  | _ -> ()

let add t uri json =
  let base_key = uri_key uri in
  Hashtbl.replace t.raw base_key json;
  Hashtbl.replace t.base_context base_key (Uri_util.without_fragment uri);
  Hashtbl.replace t.path_context base_key Json_pointer.empty;
  index_ids t ~schema_dialect:t.schema_dialect
    ~base_uri:(Uri_util.without_fragment uri)
    ~path:Json_pointer.empty json

let resolve_raw t uri =
  let frag = Uri_util.fragment uri in
  let base = Uri_util.without_fragment uri in
  let base_key = Uri.to_string base in
  (* Try exact URI (with fragment for named anchors) *)
  let full_key = Uri.to_string uri in
  match Hashtbl.find_opt t.raw full_key with
  | Some _ as found -> found
  | None -> (
      (* Try base document + JSON Pointer fragment *)
      let doc =
        match Hashtbl.find_opt t.raw base_key with
        | Some _ as found -> found
        | None -> (
            (* Call retriever with base URI (without fragment). *)
            match t.retriever with
            | Some f -> (
                let result = f base in
                match result with
                | Some json ->
                    Hashtbl.replace t.raw base_key json;
                    Hashtbl.replace t.base_context base_key base;
                    Hashtbl.replace t.path_context base_key Json_pointer.empty;
                    (* Index the fetched document so its draft-specific identifiers are known. *)
                    index_ids t ~schema_dialect:t.schema_dialect ~base_uri:base
                      ~path:Json_pointer.empty json;
                    Some json
                | None -> None)
            | None -> None)
      in
      match (doc, frag) with
      | Some doc, Some frag when frag <> "" && frag.[0] = '/' -> (
          (* JSON Pointer fragment *)
          match Json_pointer.of_string frag with
          | Ok ptr -> Json_pointer.resolve ptr doc
          | Error _ -> None)
      (* Empty fragment or no fragment = whole document. *)
      | (Some _ as found), (None | Some "") -> found
      | Some _, Some _ -> Hashtbl.find_opt t.raw full_key
      | None, _ -> None)

(** Walk a JSON Pointer path, tracking draft-specific identifier changes along
    the way. *)
let pointer_array_index_in_bounds token length =
  let token_len = String.length token in
  if length = 0 || token_len = 0 then None
  else if token_len > 1 && token.[0] = '0' then None
  else
    let max_index = length - 1 in
    let rec loop acc i =
      if i = token_len then Some acc
      else
        match token.[i] with
        | '0' .. '9' as c ->
            let digit = Char.code c - Char.code '0' in
            if acc > (max_index - digit) / 10 then None
            else loop ((acc * 10) + digit) (i + 1)
        | _ -> None
    in
    loop 0 0

let resolve_pointer_with_base t ~base_uri ptr doc =
  let rec walk base_uri json path =
    match path with
    | [] -> Some (json, base_uri)
    | token :: rest -> (
        let base_uri =
          match json with
          | `Assoc pairs -> (
              match List.assoc_opt t.schema_dialect.id_keyword pairs with
              | Some (`String id_str) ->
                  let id_uri = Uri.of_string id_str in
                  if Uri_util.fragment id_uri <> None && Uri.path id_uri = ""
                  then base_uri
                  else
                    Uri_util.without_fragment
                      (Uri_util.resolve ~base:base_uri id_uri)
              | _ -> base_uri)
          | _ -> base_uri
        in
        match json with
        | `Assoc pairs -> (
            match List.assoc_opt token pairs with
            | Some child -> walk base_uri child rest
            | None -> None)
        | `List items -> (
            match pointer_array_index_in_bounds token (List.length items) with
            | Some i -> walk base_uri (List.nth items i) rest
            | _ -> None)
        | _ -> None)
  in
  walk base_uri doc ptr

let resolve_with_base_and_path t uri =
  let frag = Uri_util.fragment uri in
  let base = Uri_util.without_fragment uri in
  let base_key = Uri.to_string base in
  (* Try exact URI first (named anchors) *)
  let full_key = Uri.to_string uri in
  match Hashtbl.find_opt t.raw full_key with
  | Some json ->
      let base_context =
        Hashtbl.find_opt t.base_context full_key |> Option.value ~default:base
      in
      let path =
        Hashtbl.find_opt t.path_context full_key
        |> Option.value ~default:Json_pointer.empty
      in
      Some (json, base_context, path)
  | None -> (
      let doc =
        match Hashtbl.find_opt t.raw base_key with
        | Some json ->
            let base_context =
              Hashtbl.find_opt t.base_context base_key
              |> Option.value ~default:base
            in
            Some (json, base_context)
        | None -> (
            match t.retriever with
            | Some f -> (
                match f base with
                | Some json ->
                    Hashtbl.replace t.raw base_key json;
                    Hashtbl.replace t.base_context base_key base;
                    Hashtbl.replace t.path_context base_key Json_pointer.empty;
                    index_ids t ~schema_dialect:t.schema_dialect ~base_uri:base
                      ~path:Json_pointer.empty json;
                    Some (json, base)
                | None -> None)
            | None -> None)
      in
      match (doc, frag) with
      | Some (doc, base_context), Some frag when frag <> "" && frag.[0] = '/'
        -> (
          match Json_pointer.of_string frag with
          | Ok ptr ->
              Option.map
                (fun (json, base_context) -> (json, base_context, ptr))
                (resolve_pointer_with_base t ~base_uri:base_context ptr doc)
          | Error _ -> None)
      | Some (json, base_context), (None | Some "") ->
          let path =
            Hashtbl.find_opt t.path_context base_key
            |> Option.value ~default:Json_pointer.empty
          in
          Some (json, base_context, path)
      | Some _, Some _ -> (
          match Hashtbl.find_opt t.raw full_key with
          | Some json ->
              let base_context =
                Hashtbl.find_opt t.base_context full_key
                |> Option.value ~default:base
              in
              let path =
                Hashtbl.find_opt t.path_context full_key
                |> Option.value ~default:Json_pointer.empty
              in
              Some (json, base_context, path)
          | None -> None)
      | _ -> None)

let resolve_with_base t uri =
  Option.map
    (fun (json, base_context, _) -> (json, base_context))
    (resolve_with_base_and_path t uri)

let dynamic_anchors_for_resource t uri =
  let key = uri_key uri in
  Hashtbl.find_opt t.dynamic_anchors key |> Option.value ~default:[]

let is_dynamic_anchor_uri t uri =
  Hashtbl.mem t.dynamic_anchor_uris (Uri.to_string uri)

let set_compiled t uri v =
  let key = Uri.to_string uri in
  let callbacks =
    match Hashtbl.find_opt t.state key with
    | Some (Compiling cbs) -> !cbs
    | _ -> []
  in
  Hashtbl.replace t.state key (Compiled v);
  List.iter (fun cb -> cb v) callbacks

let get_compiled t uri =
  let key = Uri.to_string uri in
  match Hashtbl.find_opt t.state key with
  | Some (Compiled v) -> Some v
  | _ -> None

let is_compiling t uri =
  let key = Uri.to_string uri in
  match Hashtbl.find_opt t.state key with
  | Some (Compiling _) -> true
  | _ -> false

let mark_compiling t uri =
  let key = Uri.to_string uri in
  Hashtbl.replace t.state key (Compiling (ref []))

let on_compiled t uri cb =
  let key = Uri.to_string uri in
  match Hashtbl.find_opt t.state key with
  | Some (Compiling cbs) -> cbs := cb :: !cbs
  | _ -> ()