Module: Tina4::McpDevTools

Defined in:
lib/tina4/mcp.rb

Overview

── Built-in dev tools ────────────────────────────────────────────

Class Method Summary collapse

Class Method Details

.register(server) ⇒ Object

Register all 24 built-in dev tools on the given McpServer.



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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
# File 'lib/tina4/mcp.rb', line 457

def self.register(server)
  project_root = File.expand_path(Dir.pwd)

  # ── Helpers ────────────────────────────────────────
  # Append a structured line to `.tina4/agent.log` AND echo to STDERR.
  # Mirrors the Python `_agent_log` helper so a single log file
  # captures every agent action regardless of which side of the
  # stack performed it. Cheap — never blocks the caller on I/O
  # failure.
  agent_log = lambda do |category, message|
    begin
      log_dir = File.join(project_root, ".tina4")
      FileUtils.mkdir_p(log_dir)
      log_path = File.join(log_dir, "agent.log")
      ts = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
      File.open(log_path, "a") { |f| f.write("#{ts} [#{category}] #{message}\n") }
    rescue
      # logging must never fail the actual call
    end
    warn "  [agent #{category}] #{message}"
  end

  # Paths that look like prose rather than filesystem paths. AI
  # agents occasionally pass natural language ("The plan requires
  # implementing...") as `path` to file_write and produce folders
  # with prose for names. Returns an error string on rejection,
  # nil on acceptance.
  sane_path_segment = /\A[A-Za-z0-9._\-]+\z/
  looks_like_prose = lambda do |rel_path|
    if rel_path.nil? || rel_path.strip.empty?
      break "path is empty"
    end
    if rel_path.length > 300
      break "path too long (#{rel_path.length} chars); use a real filename"
    end
    bad_sequences = ["`", "\n", "\t", "  ", "", " (", " [", "?", "*", "<", ">", "|"]
    bad_hit = bad_sequences.find { |bad| rel_path.include?(bad) }
    if bad_hit
      break "path contains illegal character sequence #{bad_hit.inspect} — looks like prose, not a filename"
    end
    segment_error = nil
    rel_path.split("/").each do |seg|
      next if seg.empty? || seg == "." || seg == ".."
      if seg.length > 80
        segment_error = "path segment too long: #{seg[0, 60].inspect}… — use a short filename"
        break
      end
      unless sane_path_segment.match?(seg)
        segment_error = "path segment #{seg.inspect} contains disallowed characters — stick to [A-Za-z0-9._-]"
        break
      end
    end
    segment_error
  end

  # Rewrite bare top-level Tina4-conventional directories into
  # their `src/<dir>/` canonical form. The framework's
  # auto-discovery only scans `src/`, so a file at
  # `templates/foo.twig` is dead weight — the framework never
  # loads it. Mirrors normalize_coder_path() in the Python agent.
  normalize_coder_path = lambda do |rel_path|
    passthrough_prefixes = ["src/", "migrations/", "plan/", "tests/",
                            "test/", ".tina4/"]
    passthrough_files = %w[app.py app.ts app.rb index.php composer.json
                           package.json Gemfile pyproject.toml
                           requirements.txt .env .env.example]
    if passthrough_prefixes.any? { |p| rel_path.start_with?(p) }
      next rel_path
    end
    if passthrough_files.include?(rel_path)
      next rel_path
    end
    %w[routes orm templates seeds controllers models middleware].each do |d|
      if rel_path.start_with?("#{d}/")
        rewritten = "src/#{rel_path}"
        agent_log.call("write.path_normalized", "#{rel_path}#{rewritten}")
        return rewritten
      end
    end
    rel_path
  end

  # Copy `target` into `.tina4/backups/` with a timestamped name.
  # Returns the relative backup path on success, nil on failure.
  agent_backup = lambda do |target|
    begin
      next nil unless File.file?(target)
      backup_dir = File.join(project_root, ".tina4", "backups")
      FileUtils.mkdir_p(backup_dir)
      rel = if target.start_with?("#{project_root}/")
              target.sub("#{project_root}/", "")
            else
              File.basename(target)
            end
      safe = rel.gsub("/", "__").gsub("\\", "__")
      ts = Time.now.utc.strftime("%Y-%m-%dT%H-%M-%SZ")
      backup_name = "#{safe}.#{ts}.bak"
      backup_path = File.join(backup_dir, backup_name)
      File.binwrite(backup_path, File.binread(target))
      ".tina4/backups/#{backup_name}"
    rescue => e
      agent_log.call("write.backup_failed", "#{target}: #{e.message}")
      nil
    end
  end

  safe_path = lambda do |rel_path|
    err = looks_like_prose.call(rel_path)
    raise ArgumentError, "Invalid path #{rel_path.inspect}: #{err}" if err
    resolved = File.expand_path(rel_path, project_root)
    unless resolved.start_with?(project_root)
      raise ArgumentError, "Path escapes project directory: #{rel_path}"
    end
    resolved
  end

  # Try `ruby -c` on a freshly-written Ruby file to catch syntax
  # errors BEFORE the next request hits the broken handler.
  # Mirrors _verify_python_import() in tina4_python/mcp/tools.py.
  #
  # Returns nil on success (or when verification is skipped), or
  # the captured error string on failure. Only checks files under
  # src/ that end in .rb — skips spec_helper.rb, *_spec.rb, and
  # test_*.rb because those have their own loading patterns
  # (mirrors Python's skip of __init__.py / conftest.py / test_*.py).
  #
  # Why this matters: the AI coder repeatedly produces Ruby with
  # unclosed blocks, missing `end`, dangling parens. Running
  # `ruby -c` right after write catches it inline and surfaces
  # the real Ruby error in the file_write response — the LLM
  # sees the error on its next turn and can retry with context.
  verify_ruby_syntax = lambda do |rel_path|
    next nil unless rel_path.end_with?(".rb")
    next nil unless rel_path.start_with?("src/")
    base = File.basename(rel_path)
    next nil if base == "spec_helper.rb"
    next nil if base.end_with?("_spec.rb")
    next nil if base.start_with?("test_")

    abs_path = File.expand_path(rel_path, project_root)
    begin
      stdout, stderr, status = Open3.capture3("ruby", "-c", abs_path)
    rescue StandardError => e
      next "verification subprocess failed: #{e.message}"
    end

    next nil if status.success?

    # Pull the first meaningful stderr line — ruby -c emits
    # "<file>:<line>: syntax error, ...". Strip the absolute
    # path prefix for readability.
    err_lines = (stderr || "").strip.split("\n")
    if err_lines.empty?
      next "syntax check failed (exit #{status.exitstatus}, no stderr)"
    end
    line = err_lines.first.strip
    # Strip the absolute project_root prefix so the error reads
    # as "src/routes/foo.rb:3: syntax error, ..." instead of the
    # full /Users/... path.
    line.sub("#{project_root}/", "")
  end

  redact_env = lambda do |key, value|
    sensitive = %w[secret password token key credential api_key]
    if sensitive.any? { |s| key.downcase.include?(s) }
      "***REDACTED***"
    else
      value
    end
  end

  # ── Database Tools ────────────────────────────────
  server.register_tool("database_query", lambda { |sql:, params: "[]"|
    db = Tina4.database
    return { "error" => "No database connection" } if db.nil?
    param_list = params.is_a?(String) ? JSON.parse(params) : params
    result = db.fetch(sql, param_list)
    { "records" => result.to_a, "count" => result.count }
  }, "Execute a read-only SQL query (SELECT)")

  server.register_tool("database_execute", lambda { |sql:, params: "[]"|
    db = Tina4.database
    return { "error" => "No database connection" } if db.nil?
    param_list = params.is_a?(String) ? JSON.parse(params) : params
    result = db.execute(sql, param_list)
    db.commit rescue nil
    { "success" => true, "affected_rows" => (result.respond_to?(:count) ? result.count : 0) }
  }, "Execute arbitrary SQL (INSERT/UPDATE/DELETE/DDL)")

  server.register_tool("database_tables", lambda {
    db = Tina4.database
    return { "error" => "No database connection" } if db.nil?
    db.tables
  }, "List all database tables")

  server.register_tool("database_columns", lambda { |table:|
    db = Tina4.database
    return { "error" => "No database connection" } if db.nil?
    db.columns(table)
  }, "Get column definitions for a table")

  # ── Route Tools ───────────────────────────────────
  server.register_tool("route_list", lambda {
    routes = Tina4::Router.routes
    routes.map do |route|
      {
        "method"        => route[:method].to_s,
        "path"          => route[:path].to_s,
        "auth_required" => !route[:auth_handler].nil?
      }
    end
  }, "List all registered routes")

  server.register_tool("route_test", lambda { |method:, path:, body: "", headers: "{}"|
    client = Tina4::TestClient.new
    header_hash = headers.is_a?(String) ? JSON.parse(headers) : headers
    m = method.upcase
    r = case m
        when "GET"    then client.get(path, headers: header_hash)
        when "POST"   then client.post(path, body: body, headers: header_hash)
        when "PUT"    then client.put(path, body: body, headers: header_hash)
        when "DELETE" then client.delete(path, headers: header_hash)
        else return { "error" => "Unsupported method: #{method}" }
        end
    { "status" => r.status, "body" => r.body, "content_type" => r.content_type }
  }, "Call a route and return the response")

  server.register_tool("swagger_spec", lambda {
    Tina4::Swagger.generate
  }, "Return the OpenAPI 3.0.3 JSON spec")

  # ── Template Tools ────────────────────────────────
  server.register_tool("template_render", lambda { |template:, data: "{}"|
    ctx = data.is_a?(String) ? JSON.parse(data) : data
    Tina4::Template.render_string(template, ctx)
  }, "Render a template string with data")

  # ── File Tools ────────────────────────────────────
  server.register_tool("file_read", lambda { |path:|
    p = safe_path.call(path)
    return "File not found: #{path}" unless File.exist?(p)
    return "Not a file: #{path}" unless File.file?(p)
    File.read(p, encoding: "utf-8")
  }, "Read a project file")

  server.register_tool("file_write", lambda { |path:, content:|
    # 1. Coder-path normalization — rewrite bare top-level Tina4
    #    directories (templates/, routes/, orm/, ...) into their
    #    src/ canonical form before resolving.
    path = normalize_coder_path.call(path)
    # 2. safe_path runs looks_like_prose then sandbox check.
    p = safe_path.call(path)

    old_bytes = File.file?(p) ? File.binread(p) : ""
    old_size = old_bytes.bytesize
    old_lines = old_bytes.count("\n")
    new_bytes = content.to_s
    new_size = new_bytes.bytesize
    new_lines = new_bytes.count("\n")
    rel = p.start_with?("#{project_root}/") ? p.sub("#{project_root}/", "") : path

    # 3. Truncation guard — refuse suspicious shrinkage on
    #    non-trivial files (>200B → <30% of size).
    if old_size > 200 && (new_size * 100) < (old_size * 30)
      msg = "REFUSED #{rel} (would shrink #{old_size}#{new_size} bytes / " \
            "#{old_lines}#{new_lines} lines, looks truncated)"
      agent_log.call("write.refused", msg)
      next { "error" => msg, "refused" => true, "old_bytes" => old_size, "new_bytes" => new_size }
    end

    # 4. Backup before overwrite.
    backup_rel = old_size > 0 ? agent_backup.call(p) : nil

    FileUtils.mkdir_p(File.dirname(p))
    File.write(p, new_bytes, encoding: "utf-8")

    # 5. Audit log.
    agent_log.call("write.ok",
                   "#{rel} (#{old_size}B/#{old_lines}L → #{new_size}B/#{new_lines}L, " \
                   "backup: #{backup_rel || '(no prior file)'})")

    result = { "written" => rel, "bytes" => new_size }
    result["backup"] = backup_rel if backup_rel

    # 6. Post-write syntax check — catch hallucinated Ruby
    #    (missing `end`, unclosed parens, etc.) before the next
    #    request hits the broken handler.
    err = verify_ruby_syntax.call(rel)
    if err
      result["import_error"] = err
      agent_log.call("write.import_failed", "#{rel}: #{err}")
    end

    result
  }, "Write or update a project file (with backup, truncation guard, audit log)")

  server.register_tool("file_list", lambda { |path: "."|
    p = safe_path.call(path)
    return { "error" => "Directory not found: #{path}" } unless File.exist?(p)
    return { "error" => "Not a directory: #{path}" } unless File.directory?(p)
    Dir.children(p).sort.map do |entry|
      full = File.join(p, entry)
      {
        "name" => entry,
        "type" => File.directory?(full) ? "dir" : "file",
        "size" => File.file?(full) ? File.size(full) : 0
      }
    end
  }, "List files in a directory")

  server.register_tool("asset_upload", lambda { |filename:, content:, encoding: "utf-8"|
    target = safe_path.call("src/public/#{filename}")
    FileUtils.mkdir_p(File.dirname(target))
    if encoding == "base64"
      require "base64"
      File.binwrite(target, Base64.decode64(content))
    else
      File.write(target, content, encoding: "utf-8")
    end
    rel = target.sub("#{project_root}/", "")
    { "uploaded" => rel, "bytes" => File.size(target) }
  }, "Upload a file to src/public/")

  # ── Migration Tools ───────────────────────────────
  server.register_tool("migration_status", lambda {
    db = Tina4.database
    return { "error" => "No database connection" } if db.nil?
    migration = Tina4::Migration.new(db)
    migration.respond_to?(:status) ? migration.status : { "info" => "Migration status not available" }
  }, "List pending and completed migrations")

  server.register_tool("migration_create", lambda { |description:|
    migration = Tina4::Migration.new(nil)
    filename = migration.create(description)
    { "created" => filename }
  }, "Create a new migration file")

  server.register_tool("migration_run", lambda {
    db = Tina4.database
    return { "error" => "No database connection" } if db.nil?
    migration = Tina4::Migration.new(db)
    result = migration.run
    { "result" => result.to_s }
  }, "Run all pending migrations")

  # ── Queue Tools ───────────────────────────────────
  server.register_tool("queue_status", lambda { |topic: "default"|
    begin
      q = Tina4::Queue.new(topic: topic)
      {
        "topic"     => topic,
        "pending"   => q.size("pending"),
        "completed" => q.size("completed"),
        "failed"    => q.size("failed")
      }
    rescue => e
      { "error" => e.message }
    end
  }, "Get queue size by status")

  # ── Session/Cache Tools ───────────────────────────
  server.register_tool("session_list", lambda {
    session_dir = File.join("data", "sessions")
    return [] unless File.directory?(session_dir)
    Dir.glob(File.join(session_dir, "*.json")).map do |f|
      begin
        data = JSON.parse(File.read(f))
        { "id" => File.basename(f, ".json"), "data" => data }
      rescue JSON::ParserError, IOError
        { "id" => File.basename(f, ".json"), "error" => "corrupt" }
      end
    end
  }, "List active sessions")

  server.register_tool("cache_stats", lambda {
    begin
      if defined?(Tina4::ResponseCache)
        cache = Tina4::ResponseCache.new
        cache.cache_stats
      else
        { "error" => "Response cache not available" }
      end
    rescue => e
      { "error" => e.message }
    end
  }, "Get response cache statistics")

  # ── ORM Tools ─────────────────────────────────────
  server.register_tool("orm_describe", lambda {
    models = []
    Tina4::ORM.subclasses.each do |cls|
      fields = cls.field_definitions.map do |name, field|
        {
          "name"        => name.to_s,
          "type"        => field[:type].to_s,
          "primary_key" => field[:primary_key] == true
        }
      end
      models << {
        "class"  => cls.name,
        "table"  => cls.respond_to?(:table_name) ? cls.table_name : cls.name.downcase,
        "fields" => fields
      }
    end
    models
  }, "List all ORM models with fields and types")

  # ── Debugging Tools ───────────────────────────────
  server.register_tool("log_tail", lambda { |lines: 50|
    log_file = File.join("logs", "debug.log")
    return [] unless File.exist?(log_file)
    all_lines = File.read(log_file, encoding: "utf-8").split("\n")
    all_lines.last([lines.to_i, all_lines.length].min)
  }, "Read recent log entries")

  server.register_tool("error_log", lambda { |limit: 20|
    begin
      if defined?(Tina4::DevAdmin) && Tina4::DevAdmin.respond_to?(:message_log)
        log = Tina4::DevAdmin.message_log
        log.respond_to?(:get) ? log.get(category: "error").first(limit.to_i) : []
      else
        []
      end
    rescue
      []
    end
  }, "Recent errors and exceptions")

  server.register_tool("env_list", lambda {
    ENV.sort.to_h { |k, v| [k, redact_env.call(k, v)] }
  }, "List environment variables (secrets redacted)")

  # ── Data Tools ────────────────────────────────────
  server.register_tool("seed_table", lambda { |table:, count: 10|
    begin
      db = Tina4.database
      return { "error" => "No database connection" } if db.nil?
      inserted = Tina4.seed_table(table, db.columns(table), count: count.to_i)
      { "table" => table, "inserted" => inserted }
    rescue => e
      { "error" => e.message }
    end
  }, "Seed a table with fake data")

  # ── File patch ────────────────────────────────────
  server.register_tool("file_patch", lambda { |path:, old_string:, new_string:, count: 1|
    # 1. Normalize, 2. safe_path (which runs the prose check).
    path = normalize_coder_path.call(path)
    p = safe_path.call(path)

    # 3. Existence check.
    next { "error" => "File not found: #{path}" } unless File.file?(p)

    original = File.read(p, encoding: "utf-8")
    occurrences = original.scan(old_string).size

    # 4. Match-count guard (already-existing behaviour).
    next { "error" => "old_string not found in #{path}" } if occurrences.zero?
    if occurrences != count.to_i
      next({ "error" => "old_string appears #{occurrences} times, expected #{count}. Expand old_string to make it unique, or set count explicitly." })
    end

    updated = original.sub(old_string, new_string)
    # Ruby String#sub replaces first; if count > 1, do N replacements
    if count.to_i > 1
      updated = original.dup
      count.to_i.times { updated.sub!(old_string, new_string) }
    end

    rel = p.start_with?("#{project_root}/") ? p.sub("#{project_root}/", "") : path

    # 5. Backup before overwrite — same path layout as file_write
    #    so recovery is uniform regardless of which tool touched
    #    the file.
    backup_rel = agent_backup.call(p)

    File.write(p, updated, encoding: "utf-8")

    Tina4::Plan.record_action("patched", rel) if defined?(Tina4::Plan)

    old_size = original.bytesize
    new_size = updated.bytesize
    agent_log.call("patch.ok",
                   "#{rel} (replaced #{count.to_i}× old_string, " \
                   "#{old_size}B → #{new_size}B, backup: #{backup_rel || '(none)'})")

    result = { "patched" => rel, "replacements" => count.to_i, "bytes" => new_size }
    result["backup"] = backup_rel if backup_rel

    # Post-patch syntax check — same rationale as file_write.
    err = verify_ruby_syntax.call(rel)
    if err
      result["import_error"] = err
      agent_log.call("patch.import_failed", "#{rel}: #{err}")
    end

    result
  }, "Targeted edit: replace old_string with new_string in a file (with backup + audit log)")

  # ── Docs tools ────────────────────────────────────
  framework_doc_paths = lambda do
    gem_root = File.expand_path("..", File.dirname(__FILE__))
    candidates = [
      File.join(gem_root, "..", "CLAUDE.md"),
      File.join(gem_root, "..", "AGENTS.md"),
      File.join(gem_root, "..", "CONVENTIONS.md"),
      File.join(gem_root, "..", "README.md"),
      File.join(Dir.pwd, "CLAUDE.md")
    ]
    candidates.map { |p| File.expand_path(p) }.uniq.select { |p| File.file?(p) }
  end

  server.register_tool("docs_list", lambda {
    framework_doc_paths.call.map { |p| { "name" => File.basename(p), "bytes" => File.size(p) } }
  }, "List framework documentation files")

  server.register_tool("docs_search", lambda { |query:, limit: 5, context_lines: 4|
    return { "error" => "query must be at least 2 characters" } if query.to_s.length < 2
    needle = query.to_s.downcase
    hits = []
    framework_doc_paths.call.each do |p|
      begin
        lines = File.read(p, encoding: "utf-8", invalid: :replace, undef: :replace).split("\n")
      rescue StandardError
        next
      end
      lines.each_with_index do |line, i|
        next unless line.downcase.include?(needle)
        start_i = [0, i - context_lines.to_i].max
        end_i   = [lines.size, i + context_lines.to_i + 1].min
        score = 1
        score += 1 if line.include?(query.to_s)
        score += 2 if line.lstrip.start_with?("#")
        hits << {
          "file" => File.basename(p),
          "line" => i + 1,
          "score" => score,
          "snippet" => lines[start_i...end_i].join("\n")
        }
      end
    end
    hits.sort_by! { |h| -h["score"] }
    hits.first([1, limit.to_i].max)
  }, "Search Tina4 framework docs for a query string")

  server.register_tool("docs_section", lambda { |file:, heading:|
    match = framework_doc_paths.call.find { |p| File.basename(p) == file }
    return { "error" => "Unknown doc file: #{file}. Try docs_list() first." } unless match
    text = File.read(match, encoding: "utf-8", invalid: :replace, undef: :replace)
    lines = text.split("\n")
    heading_lc = heading.to_s.downcase.strip
    start_i = -1
    start_level = 0
    lines.each_with_index do |line, i|
      stripped = line.lstrip
      next unless stripped.start_with?("#")
      level = stripped.length - stripped.sub(/\A#+/, "").length
      title = stripped[level..].to_s.strip.downcase
      if title.include?(heading_lc)
        start_i = i
        start_level = level
        break
      end
    end
    return { "error" => "Heading '#{heading}' not found in #{file}" } if start_i < 0
    end_i = lines.size
    (start_i + 1).upto(lines.size - 1) do |j|
      stripped = lines[j].lstrip
      next unless stripped.start_with?("#")
      level = stripped.length - stripped.sub(/\A#+/, "").length
      if level <= start_level
        end_i = j
        break
      end
    end
    { "file" => file, "heading" => lines[start_i].strip, "body" => lines[start_i...end_i].join("\n") }
  }, "Return a full markdown section from a framework doc file")

  # ── Git / deps / project ──────────────────────────
  server.register_tool("git_status", lambda {
    Tina4::DevAdmin.send(:git_status_payload)
  }, "Show git branch, modified/untracked files, recent commits")

  server.register_tool("deps_list", lambda {
    gemfile = File.join(Dir.pwd, "Gemfile")
    return { "error" => "No Gemfile at project root" } unless File.file?(gemfile)
    deps = File.read(gemfile).scan(/^\s*gem\s+["']([^"']+)["']/).flatten
    { "name" => File.basename(Dir.pwd), "dependencies" => deps }
  }, "List this project's declared Ruby dependencies")

  server.register_tool("project_overview", lambda {
    { "system" => { "framework" => "tina4-ruby", "version" => (defined?(Tina4::VERSION) ? Tina4::VERSION : "unknown"), "ruby" => RUBY_DESCRIPTION, "cwd" => project_root } }
  }, "One-shot snapshot: system + project info")

  # ── Project index ─────────────────────────────────
  server.register_tool("index_rebuild", lambda {
    Tina4::ProjectIndex.refresh
  }, "Refresh the persistent project index (lazy, mtime-based)")

  server.register_tool("index_search", lambda { |query:, limit: 20|
    Tina4::ProjectIndex.search(query, limit.to_i)
  }, "Find files by path, symbol, route, or summary")

  server.register_tool("index_file", lambda { |path:|
    Tina4::ProjectIndex.file_entry(path)
  }, "Full index entry for one file")

  server.register_tool("index_overview", lambda {
    Tina4::ProjectIndex.overview
  }, "Project shape: files by language, routes, models, recent edits")

  # ── Plan management ───────────────────────────────
  server.register_tool("plan_current", lambda {
    Tina4::Plan.current
  }, "The active plan: title, steps (done/not), next step, progress")

  server.register_tool("plan_list", lambda {
    Tina4::Plan.list_plans
  }, "All plans in plan/ with progress and which one is active")

  server.register_tool("plan_create", lambda { |title:, goal: "", steps: nil, make_current: true|
    Tina4::Plan.create(title, goal: goal, steps: steps, make_current: make_current)
  }, "Create a new markdown plan in plan/ and make it active")

  server.register_tool("plan_switch_to", lambda { |name:|
    Tina4::Plan.set_current(name)
  }, "Make a different plan the active one")

  server.register_tool("plan_complete_step", lambda { |index:|
    Tina4::Plan.complete_step(index.to_i)
  }, "Tick a step as done (call the moment the step finishes)")

  server.register_tool("plan_add_step", lambda { |text:|
    Tina4::Plan.add_step(text)
  }, "Append a new unchecked step to the current plan")

  server.register_tool("plan_note", lambda { |text:|
    Tina4::Plan.append_note(text)
  }, "Append a timestamped note/breadcrumb to the current plan")

  server.register_tool("plan_archive", lambda { |name: ""|
    Tina4::Plan.archive(name)
  }, "Move a finished plan to plan/done/")

  server.register_tool("plan_read", lambda { |name:|
    Tina4::Plan.read(name)
  }, "Full structured view of any plan by filename")

  server.register_tool("plan_flesh", lambda { |name: "", prompt: ""|
    Tina4::Plan.flesh(name, prompt)
  }, "Auto-generate concrete build steps via AI and append them to an existing plan")

  # ── Live API Docs (Live API RAG) ──────────────────
  server.register_tool("api_search", lambda { |query:, k: 5, source: "all", include_private: false|
    Tina4::Docs.cached(project_root).search(
      query.to_s, k: k.to_i, source: source.to_s, include_private: include_private == true || include_private.to_s == "true"
    )
  }, "Search the live API index (framework + user code) for ranked hits")

  server.register_tool("api_class", lambda { |name:|
    Tina4::Docs.cached(project_root).class_spec(name.to_s)
  }, "Full class reflection (methods, file, line) from the live API index")

  server.register_tool("api_method", lambda { |class_name:, name:|
    Tina4::Docs.cached(project_root).method_spec(class_name.to_s, name.to_s)
  }, "Single method spec (signature, summary, file, line) from the live API index")

  # ── System Tools ──────────────────────────────────
  server.register_tool("system_info", lambda {
    {
      "framework" => "tina4-ruby",
      "version"   => (defined?(Tina4::VERSION) ? Tina4::VERSION : "unknown"),
      "ruby"      => RUBY_DESCRIPTION,
      "platform"  => RUBY_PLATFORM,
      "cwd"       => project_root,
      "debug"     => ENV.fetch("TINA4_DEBUG", "false")
    }
  }, "Framework version, Ruby version, project info")
end