Skip to content

Commit 5766f3c

Browse files
author
Josh Bendson
committed
style: Apply black formatting to server code
Run black formatter on server and test files for CI compliance. Changes: - Line break adjustments for better readability - Consistent formatting across delegation, MCP, health, and test files - No functional changes Note: Required by server-fast-automation.sh black formatting check. Pre-existing mypy type errors remain in some files (separate issue).
1 parent 355f533 commit 5766f3c

41 files changed

Lines changed: 708 additions & 459 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

src/code_indexer/server/clients/claude_server_client.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ async def authenticate(self) -> str:
107107
# Claude Server returns "expires" (ISO datetime), standard returns "expires_in" (seconds)
108108
if "expires" in data:
109109
from dateutil.parser import parse as parse_datetime
110+
110111
self._jwt_expires = parse_datetime(data["expires"])
111112
else:
112113
expires_in = data.get("expires_in", 3600)
@@ -194,9 +195,7 @@ async def _make_authenticated_request(
194195
)
195196
elif response.status_code == 401 and not retry_on_401:
196197
# Second 401 means auth truly failed - raise exception
197-
raise ClaudeServerAuthError(
198-
"Authentication failed after token refresh"
199-
)
198+
raise ClaudeServerAuthError("Authentication failed after token refresh")
200199

201200
return response
202201

@@ -250,9 +249,7 @@ async def register_repository(
250249
f"Repository registration failed: HTTP {response.status_code}"
251250
)
252251

253-
async def create_job(
254-
self, prompt: str, repositories: List[str]
255-
) -> Dict[str, Any]:
252+
async def create_job(self, prompt: str, repositories: List[str]) -> Dict[str, Any]:
256253
"""
257254
Create a new job with the given prompt.
258255
@@ -276,13 +273,9 @@ async def create_job(
276273
if response.status_code in (200, 201):
277274
return response.json()
278275
elif response.status_code >= 500:
279-
raise ClaudeServerError(
280-
f"Claude Server error: HTTP {response.status_code}"
281-
)
276+
raise ClaudeServerError(f"Claude Server error: HTTP {response.status_code}")
282277
else:
283-
raise ClaudeServerError(
284-
f"Job creation failed: HTTP {response.status_code}"
285-
)
278+
raise ClaudeServerError(f"Job creation failed: HTTP {response.status_code}")
286279

287280
async def start_job(self, job_id: str) -> Dict[str, Any]:
288281
"""

src/code_indexer/server/config/delegation_config.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ class ClaudeDelegationConfig:
5252
claude_server_credential_type: Literal["password", "api_key"] = "password"
5353
claude_server_credential: str = "" # Encrypted at rest
5454
skip_ssl_verify: bool = False # Allow self-signed certificates for E2E testing
55-
cidx_callback_url: str = "" # Story #720: URL that Claude Server uses to POST callbacks
55+
cidx_callback_url: str = (
56+
"" # Story #720: URL that Claude Server uses to POST callbacks
57+
)
5658

5759
@property
5860
def is_configured(self) -> bool:

src/code_indexer/server/mcp/handlers.py

Lines changed: 108 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -8852,7 +8852,9 @@ def _get_delegation_function_repo_path() -> Optional[Path]:
88528852
repo_path = golden_repo_manager.get_actual_repo_path(function_repo_alias)
88538853
return Path(repo_path) if repo_path else None
88548854
except Exception as e:
8855-
logger.warning(f"Function repository '{function_repo_alias}' not found: {e}")
8855+
logger.warning(
8856+
f"Function repository '{function_repo_alias}' not found: {e}"
8857+
)
88568858
return None
88578859

88588860
except Exception as e:
@@ -8974,7 +8976,9 @@ def _get_delegation_config():
89748976
return None
89758977

89768978

8977-
def _validate_function_parameters(target_function, parameters: Dict[str, Any]) -> Optional[str]:
8979+
def _validate_function_parameters(
8980+
target_function, parameters: Dict[str, Any]
8981+
) -> Optional[str]:
89788982
"""
89798983
Validate required parameters are present.
89808984
@@ -8989,7 +8993,9 @@ def _validate_function_parameters(target_function, parameters: Dict[str, Any]) -
89898993
return None
89908994

89918995

8992-
async def _ensure_repos_registered(client, required_repos: List[Dict[str, Any]]) -> List[str]:
8996+
async def _ensure_repos_registered(
8997+
client, required_repos: List[Dict[str, Any]]
8998+
) -> List[str]:
89938999
"""
89949000
Ensure required repositories are registered in Claude Server.
89959001
@@ -9064,8 +9070,14 @@ async def handle_execute_delegation_function(
90649070
repo_path = _get_delegation_function_repo_path()
90659071
delegation_config = _get_delegation_config()
90669072

9067-
if repo_path is None or delegation_config is None or not delegation_config.is_configured:
9068-
return _mcp_response({"success": False, "error": "Claude Delegation not configured"})
9073+
if (
9074+
repo_path is None
9075+
or delegation_config is None
9076+
or not delegation_config.is_configured
9077+
):
9078+
return _mcp_response(
9079+
{"success": False, "error": "Claude Delegation not configured"}
9080+
)
90699081

90709082
function_name = args.get("function_name", "")
90719083
parameters = args.get("parameters", {})
@@ -9074,17 +9086,27 @@ async def handle_execute_delegation_function(
90749086
# Load and find function
90759087
loader = DelegationFunctionLoader()
90769088
all_functions = loader.load_functions(repo_path)
9077-
target_function = next((f for f in all_functions if f.name == function_name), None)
9089+
target_function = next(
9090+
(f for f in all_functions if f.name == function_name), None
9091+
)
90789092

90799093
if target_function is None:
9080-
return _mcp_response({"success": False, "error": f"Function not found: {function_name}"})
9094+
return _mcp_response(
9095+
{"success": False, "error": f"Function not found: {function_name}"}
9096+
)
90819097

90829098
# Access validation
9083-
effective_user = session_state.effective_user if session_state and session_state.is_impersonating else user
9099+
effective_user = (
9100+
session_state.effective_user
9101+
if session_state and session_state.is_impersonating
9102+
else user
9103+
)
90849104
user_groups = _get_user_groups(effective_user)
90859105

90869106
if not (user_groups & set(target_function.allowed_groups)):
9087-
return _mcp_response({"success": False, "error": "Access denied: insufficient permissions"})
9107+
return _mcp_response(
9108+
{"success": False, "error": "Access denied: insufficient permissions"}
9109+
)
90889110

90899111
# Parameter validation
90909112
param_error = _validate_function_parameters(target_function, parameters)
@@ -9099,31 +9121,43 @@ async def handle_execute_delegation_function(
90999121
password=delegation_config.claude_server_credential,
91009122
skip_ssl_verify=delegation_config.skip_ssl_verify,
91019123
) as client:
9102-
repo_aliases = await _ensure_repos_registered(client, target_function.required_repos)
9124+
repo_aliases = await _ensure_repos_registered(
9125+
client, target_function.required_repos
9126+
)
91039127

91049128
# Render prompt and create job
91059129
processor = PromptTemplateProcessor()
9106-
impersonation_user = target_function.impersonation_user or effective_user.username
9130+
impersonation_user = (
9131+
target_function.impersonation_user or effective_user.username
9132+
)
91079133
rendered_prompt = processor.render(
91089134
template=target_function.prompt_template,
91099135
parameters=parameters,
91109136
user_prompt=user_prompt,
91119137
impersonation_user=impersonation_user,
91129138
)
91139139

9114-
job_result = await client.create_job(prompt=rendered_prompt, repositories=repo_aliases)
9140+
job_result = await client.create_job(
9141+
prompt=rendered_prompt, repositories=repo_aliases
9142+
)
91159143
# Claude Server returns camelCase "jobId"
91169144
job_id = job_result.get("jobId") or job_result.get("job_id")
91179145
if not job_id:
9118-
return _mcp_response({"success": False, "error": "Job created but no job_id returned"})
9146+
return _mcp_response(
9147+
{"success": False, "error": "Job created but no job_id returned"}
9148+
)
91199149

91209150
# Story #720: Register callback URL with Claude Server for completion notification
91219151
callback_base_url = _get_cidx_callback_base_url()
91229152
if callback_base_url:
9123-
callback_url = f"{callback_base_url.rstrip('/')}/api/delegation/callback/{job_id}"
9153+
callback_url = (
9154+
f"{callback_base_url.rstrip('/')}/api/delegation/callback/{job_id}"
9155+
)
91249156
try:
91259157
await client.register_callback(job_id, callback_url)
9126-
logger.debug(f"Registered callback URL for job {job_id}: {callback_url}")
9158+
logger.debug(
9159+
f"Registered callback URL for job {job_id}: {callback_url}"
9160+
)
91279161
except Exception as callback_err:
91289162
# Log but don't fail - callback registration is best-effort
91299163
logger.warning(
@@ -9142,10 +9176,15 @@ async def handle_execute_delegation_function(
91429176
return _mcp_response({"success": True, "job_id": job_id})
91439177

91449178
except ClaudeServerError as e:
9145-
logger.error(f"Claude Server error: {e}", extra={"correlation_id": get_correlation_id()})
9179+
logger.error(
9180+
f"Claude Server error: {e}", extra={"correlation_id": get_correlation_id()}
9181+
)
91469182
return _mcp_response({"success": False, "error": f"Claude Server error: {e}"})
91479183
except Exception as e:
9148-
logger.exception(f"Error in execute_delegation_function: {e}", extra={"correlation_id": get_correlation_id()})
9184+
logger.exception(
9185+
f"Error in execute_delegation_function: {e}",
9186+
extra={"correlation_id": get_correlation_id()},
9187+
)
91499188
return _mcp_response({"success": False, "error": str(e)})
91509189

91519190

@@ -9179,66 +9218,87 @@ async def handle_poll_delegation_job(
91799218
delegation_config = _get_delegation_config()
91809219

91819220
if delegation_config is None or not delegation_config.is_configured:
9182-
return _mcp_response({"success": False, "error": "Claude Delegation not configured"})
9221+
return _mcp_response(
9222+
{"success": False, "error": "Claude Delegation not configured"}
9223+
)
91839224

91849225
job_id = args.get("job_id", "")
91859226
if not job_id:
9186-
return _mcp_response({"success": False, "error": "Missing required parameter: job_id"})
9227+
return _mcp_response(
9228+
{"success": False, "error": "Missing required parameter: job_id"}
9229+
)
91879230

91889231
# Story #720: Get timeout_seconds from args (default 45s, below MCP's 60s)
91899232
# Also support legacy "timeout" parameter for backward compatibility
91909233
timeout = args.get("timeout_seconds", args.get("timeout", 45))
91919234
if not isinstance(timeout, (int, float)):
9192-
return _mcp_response({
9193-
"success": False,
9194-
"error": "timeout_seconds must be a number (recommended: 5-300)"
9195-
})
9235+
return _mcp_response(
9236+
{
9237+
"success": False,
9238+
"error": "timeout_seconds must be a number (recommended: 5-300)",
9239+
}
9240+
)
91969241
# Minimum 0.01s (for testing), maximum 300s (5 minutes)
91979242
# Recommended range for production: 5-300 seconds
91989243
if timeout < 0.01 or timeout > 300:
9199-
return _mcp_response({
9200-
"success": False,
9201-
"error": "timeout_seconds must be between 0.01 and 300"
9202-
})
9244+
return _mcp_response(
9245+
{
9246+
"success": False,
9247+
"error": "timeout_seconds must be between 0.01 and 300",
9248+
}
9249+
)
92039250

92049251
# Check if job exists in tracker before waiting
92059252
tracker = DelegationJobTracker.get_instance()
92069253
job_exists = await tracker.has_job(job_id)
92079254
if not job_exists:
9208-
return _mcp_response({
9209-
"success": False,
9210-
"error": f"Job {job_id} not found or already completed",
9211-
})
9255+
return _mcp_response(
9256+
{
9257+
"success": False,
9258+
"error": f"Job {job_id} not found or already completed",
9259+
}
9260+
)
92129261

92139262
# Wait for callback via DelegationJobTracker
92149263
result = await tracker.wait_for_job(job_id, timeout=timeout)
92159264

92169265
if result is None:
92179266
# Timeout - job still exists, caller can try again
9218-
return _mcp_response({
9219-
"status": "waiting",
9220-
"message": "Job still running, callback not yet received",
9221-
"continue_polling": True,
9222-
})
9267+
return _mcp_response(
9268+
{
9269+
"status": "waiting",
9270+
"message": "Job still running, callback not yet received",
9271+
"continue_polling": True,
9272+
}
9273+
)
92239274

92249275
# Return result based on status from callback
92259276
if result.status == "completed":
9226-
return _mcp_response({
9227-
"status": "completed",
9228-
"result": result.output,
9229-
"continue_polling": False,
9230-
})
9277+
return _mcp_response(
9278+
{
9279+
"status": "completed",
9280+
"result": result.output,
9281+
"continue_polling": False,
9282+
}
9283+
)
92319284
else:
92329285
# Failed or other status
9233-
return _mcp_response({
9234-
"status": "failed",
9235-
"error": result.error or result.output,
9236-
"continue_polling": False,
9237-
})
9286+
return _mcp_response(
9287+
{
9288+
"status": "failed",
9289+
"error": result.error or result.output,
9290+
"continue_polling": False,
9291+
}
9292+
)
92389293

92399294
except Exception as e:
9240-
logger.error(f"Error waiting for delegation job {job_id}: {e}", extra={"correlation_id": get_correlation_id()})
9241-
return _mcp_response({"success": False, "error": f"Error waiting for job completion: {str(e)}"})
9295+
logger.error(
9296+
f"Error waiting for delegation job {job_id}: {e}",
9297+
extra={"correlation_id": get_correlation_id()},
9298+
)
9299+
return _mcp_response(
9300+
{"success": False, "error": f"Error waiting for job completion: {str(e)}"}
9301+
)
92429302

92439303

92449304
HANDLER_REGISTRY["poll_delegation_job"] = handle_poll_delegation_job

src/code_indexer/server/mcp/session_registry.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@ def __new__(cls) -> "SessionRegistry":
8282
# TTL cleanup attributes (Story #731)
8383
instance._cleanup_task: Optional[asyncio.Task] = None
8484
instance._ttl_seconds = DEFAULT_SESSION_TTL_SECONDS
85-
instance._cleanup_interval_seconds = DEFAULT_CLEANUP_INTERVAL_SECONDS
85+
instance._cleanup_interval_seconds = (
86+
DEFAULT_CLEANUP_INTERVAL_SECONDS
87+
)
8688
cls._instance = instance
8789
return cls._instance
8890

src/code_indexer/server/mcp/tools.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7410,7 +7410,13 @@ def filter_tools_by_role(user: User) -> List[Dict[str, Any]]:
74107410
},
74117411
"phase": {
74127412
"type": "string",
7413-
"enum": ["repo_registration", "repo_cloning", "cidx_indexing", "job_running", "done"],
7413+
"enum": [
7414+
"repo_registration",
7415+
"repo_cloning",
7416+
"cidx_indexing",
7417+
"job_running",
7418+
"done",
7419+
],
74147420
"description": "Current phase of job execution",
74157421
},
74167422
"progress": {

src/code_indexer/server/query/semantic_query_manager.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -979,13 +979,15 @@ def _search_single_repository(
979979
# Story #725: Only warn when non-default filters are explicitly set
980980
# Note: accuracy="balanced" is the default, so we only warn if accuracy
981981
# is set to something other than "balanced" or None
982-
has_non_default_filters = any([
983-
language, # None is default
984-
exclude_language, # None is default
985-
path_filter, # None is default
986-
exclude_path, # None is default
987-
accuracy and accuracy != "balanced" # "balanced" is default
988-
])
982+
has_non_default_filters = any(
983+
[
984+
language, # None is default
985+
exclude_language, # None is default
986+
path_filter, # None is default
987+
exclude_path, # None is default
988+
accuracy and accuracy != "balanced", # "balanced" is default
989+
]
990+
)
989991
if search_mode in ["semantic", "hybrid"] and has_non_default_filters:
990992
self.logger.warning(
991993
f"Advanced filter parameters (language={language}, exclude_language={exclude_language}, "

src/code_indexer/server/routers/delegation_callbacks.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,9 @@ class CallbackPayload(BaseModel):
3939
Repository: Optional[str] = Field(None, description="Repository alias")
4040
CreatedAt: Optional[datetime] = Field(None, description="Job creation timestamp")
4141
StartedAt: Optional[datetime] = Field(None, description="Job start timestamp")
42-
CompletedAt: Optional[datetime] = Field(None, description="Job completion timestamp")
42+
CompletedAt: Optional[datetime] = Field(
43+
None, description="Job completion timestamp"
44+
)
4345
ReferenceId: Optional[str] = Field(None, description="Reference ID for tracking")
4446
AffinityToken: Optional[str] = Field(None, description="Affinity token for routing")
4547

@@ -75,9 +77,7 @@ async def receive_delegation_callback(
7577
Returns:
7678
CallbackResponse indicating receipt and whether job was found
7779
"""
78-
logger.info(
79-
f"Received callback for job {job_id}: status={payload.Status}"
80-
)
80+
logger.info(f"Received callback for job {job_id}: status={payload.Status}")
8181

8282
tracker = DelegationJobTracker.get_instance()
8383

0 commit comments

Comments
 (0)